In this blogging you know about digital world.
- Get link
- X
- Other Apps
Methods and Classes
Methods and Classes
Methods:
1. Definition: A method in Java is a block of code that performs a specific task. It is
a set of instructions encapsulated within a block and can be invoked (called)
to perform that task.
2. Method Signature: A method signature includes the method's name and its
parameter list. The return type is also considered part of the method signature
when overloading methods.
In Java, a method signature is a
combination of a method's name and its parameter list. The method signature is
used to uniquely identify and differentiate one method from another. It plays a
crucial role in method overloading, where you can have multiple methods with
the same name but different parameter lists. The return type is not considered
part of the method signature.
A method
signature consists of the following components:
i. Method Name: The name of the method, which is used to identify it. This name should
follow the Java identifier rules and conventions.
ii. Parameter List: The list of parameters (also known as formal parameters)
enclosed in parentheses. Each parameter includes its data type and a name. The
order, data types, and number of parameters in the list make up the method's
signature
Here's a simple example to illustrate method
signatures:
public class
MyClass {
// Method with no parameters
public void printHello() {
System.out.println("Hello!");
}
// Method with one parameter (int)
public void printNumber(int num) {
System.out.println("Number: "
+ num);
}
// Method with two parameters (String and
int)
public void printDetails(String name, int
age) {
System.out.println("Name: " +
name + ", Age: " + age);
}
}
In the
above code:
- The method
`printHello` has a method signature of `printHello()`, with no parameters.
- The method
`printNumber` has a method signature of `printNumber(int num)`, with one `int`
parameter.
- The method
`printDetails` has a method signature of `printDetails(String name, int age)`,
with one `String` and one `int` parameter.
These method
signatures uniquely identify each method within the class, allowing you to
overload methods by providing different parameter lists. For example, you could
have another method named `printDetails` with a different set of parameters,
and Java would still be able to distinguish between them based on their method
signatures.
3. Access Modifiers: Methods can have access modifiers that control their
visibility and accessibility. Common access modifiers include `public`,
`private`, `protected`, and package-private (default).
4. Return Type: A method can return a value using a specified data type. If a method
does not return a value, its return type is `void`.
5. Parameters: Methods can accept zero or more parameters (input values). Parameters
are declared within parentheses after the method name.
6. Method Overloading: As mentioned earlier, method overloading allows you to
define multiple methods with the same name but different parameter lists.
Method overloading in Java allows you to define multiple
methods in a class with the same name but different parameter lists. This
enables you to create more flexible and intuitive APIs for your classes by
providing multiple ways to call a method, depending on the arguments passed.
When a class has two or more methods by the same name but
different parameters, it is known as method overloading. It is different from
overriding. In overriding, a method has the same method name, type, number of
parameters, etc.
Let’s
consider the example discussed earlier for finding minimum numbers of integer
type. If, let’s say we want to find the minimum number of double type. Then the
concept of overloading will be introduced to create two or more methods with
the same name but different parameters.
The following example explains the same −
Example
public class
ExampleOverloading {
public static void main(String[] args) {
int a = 11;
int b = 6;
double c =
7.3;
double d =
9.4;
int result1 = minFunction(a, b);
// same function name with different
parameters
double result2 = minFunction(c, d);
System.out.println("Minimum Value =
" + result1);
System.out.println("Minimum Value =
" + result2);
}
// for integer
public static int minFunction(int n1, int
n2) {
int min;
if (n1 > n2)
min = n2;
else
min = n1;
return min;
}
// for double
public static double minFunction(double n1,
double n2) {
double min;
if (n1 > n2)
min = n2;
else
min = n1;
return min;
}
}
This will
produce the following result −
Output
Minimum
Value = 6
Minimum
Value = 7.3
Overloading
methods makes program readable. Here, two methods are given by the same name
but with different parameters. The minimum number from integer and double types
is the result.
Using Command-Line Arguments: Sometimes you will want to pass some information into
a program when you run it. This is accomplished by passing command-line
arguments to main( ).
A
command-line argument is the information that directly follows the program's
name on the command line when it is executed. To access the command-line
arguments inside a Java program is quite easy. They are stored as strings in
the String array passed to main( ).
Example
The
following program displays all of the command-line arguments that it is called
with −
public class
CommandLine {
public static void main(String args[]) {
for(int i = 0; i<args.length; i++) {
System.out.println("args[" +
i + "]: " + args[i]);
}
}
}
Try
executing this program as shown here −
$java
CommandLine this is a command line 200 -100
This will
produce the following result −
Output
args[0]:
this
args[1]: is
args[2]: a
args[3]:
command
args[4]:
line
args[5]: 200
args[6]:
-100
The this keyword: this is a keyword in Java which is used as a reference to the
object of the current class, with in an instance method or a constructor. Using
this you can refer the members of a class such as constructors, variables and
methods.
This
In general,
the keyword this is used to differentiate the instance variables from local
variables if they have same names, within a constructor or a method.
class
Student {
int age;
Student(int age) {
this.age = age;
}
}
Call one
type of constructor (parametrized constructor or default) from other in a
class. It is known as explicit constructor invocation.
class
Student {
int age
Student() {
this(20);
}
Student(int age) {
this.age = age;
}
}
Example
Here is an
example that uses this keyword to access the members of a class. Copy and paste
the following program in a file with the name, This_Example.java.
public class
This_Example {
// Instance variable num
int num = 10;
This_Example() {
System.out.println("This is an
example program on keyword this");
}
This_Example(int num) {
// Invoking the default constructor
this();
// Assigning the local variable num to
the instance variable num
this.num = num;
}
public void greet() {
System.out.println("Hi Welcome to
Tutorialspoint");
}
public void print() {
// Local variable num
int num = 20;
// Printing the local variable
System.out.println("value of local
variable num is : "+num);
// Printing the instance variable
System.out.println("value of
instance variable num is : "+this.num);
// Invoking the greet method of a class
this.greet();
}
public static void main(String[] args) {
// Instantiating the class
This_Example obj1 = new This_Example();
// Invoking the print method
obj1.print();
// Passing a new value to the num
variable through parametrized constructor
This_Example obj2 = new This_Example(30);
// Invoking the print method again
obj2.print();
}
}
This will
produce the following result −
Output
This is an
example program on keyword this
value of
local variable num is : 20
value of
instance variable num is : 10
Hi Welcome
to Tutorialspoint
This is an
example program on keyword this
value of
local variable num is : 20
value of
instance variable num is : 30
Hi Welcome
to Tutorialspoint
Variable
Arguments(var-args): JDK
1.5 enables you to pass a variable number of arguments of the same type to a
method. The parameter in the method is declared as follows −
typeName...
parameterName: In the
method declaration, you specify the type followed by an ellipsis (...). Only
one variable-length parameter may be specified in a method, and this parameter
must be the last parameter. Any regular parameters must precede it.
Example:
public class
VarargsDemo {
public static void main(String args[]) {
// Call method with variable args
printMax(34, 3, 3, 2, 56.5);
printMax(new double[]{1, 2, 3});
}
public static void printMax( double...
numbers) {
if (numbers.length == 0) {
System.out.println("No argument
passed");
return;
}
double result = numbers[0];
for (int i = 1; i < numbers.length; i++)
if (numbers[i] > result)
result = numbers[i];
System.out.println("The max value is
" + result);
}
}
This will
produce the following result −
Output
The max
value is 56.5
The max
value is 3.0
The finalize( ) Method: It is possible to define a method that will be called just
before an object's final destruction by the garbage collector. This method is
called finalize( ), and it can be used to ensure that an object terminates
cleanly.
For example,
you might use finalize( ) to make sure that an open file owned by that object
is closed.
To add a
finalizer to a class, you simply define the finalize( ) method. The Java
runtime calls that method whenever it is about to recycle an object of that
class.
Inside the
finalize( ) method, you will specify those actions that must be performed
before an object is destroyed.
The
finalize( ) method has this general form −
protected
void finalize( ) {
// finalization code here
}
Here, the
keyword protected is a specifier that prevents access to finalize( ) by code
defined outside its class.
This means
that you cannot know when or even if finalize( ) will be executed. For example,
if your program ends before garbage collection occurs, finalize( ) will not
execute.
Here's an example of method overloading in Java:
public class
Calculator {
public int add(int a, int b) {
return a + b;
}
public double add(double a, double b) {
return a + b;
}
public int add(int a, int b, int c) {
return a + b + c;
}
public String add(String str1, String str2)
{
return str1 + str2;
}
public static void main(String[] args) {
Calculator calculator = new
Calculator();
System.out.println(calculator.add(2,
3)); // Calls the first add
method
System.out.println(calculator.add(2.5,
3.7)); // Calls the second add
method
System.out.println(calculator.add(1, 2,
3)); // Calls the third add
method
System.out.println(calculator.add("Hello, ",
"world!")); // Calls the fourth add method
}
}
In this
example, the `Calculator` class has multiple `add` methods, each with a
different parameter list. Depending on the arguments you pass when calling the
`add` method, Java will determine which version of the method to invoke.
Method
overloading allows you to create more readable and expressive code by providing
different ways to call a method based on the context and data types you have.
7. Method Invocation: To use a method, you call it by its name and pass arguments
(if required) enclosed in parentheses. For example: `methodName(argument1,
argument2)`.
Example of a
Method:
public class
MyMath {
public int add(int a, int b) {
return a + b;
}
}
In the above
example, `add` is a method that takes two integer parameters and returns their
sum.
Classes:
1. Definition: In Java, a class is a blueprint or template for creating objects. It
defines the structure and behavior of objects that can be created based on that
class.
2. Fields (Instance Variables): Classes can have fields, also known as instance
variables, which represent the state of an object. These variables store data
that belongs to an instance of the class.
3. Methods (Member Functions): Classes can contain methods that define the behavior
of objects created from the class. Methods are responsible for performing tasks
and operations on the class's data.
4. Constructors: A constructor is a special method used to initialize an object when it
is created. It has the same name as the class and is typically used to set
initial values for the object's fields.
5. Access Modifiers: Like methods, fields and classes themselves can have access
modifiers to control their visibility and accessibility.
Example of a Class:
public class
Student {
// Fields
private String name;
private int age;
// Constructor
public Student(String name, int age) {
this.name = name;
this.age = age;
}
// Method to get student's name
public String getName() {
return name;
}
// Method to set student's age
public void setAge(int age) {
this.age = age;
}
}
In the above
example, `Student` is a class with fields (`name` and `age`), a constructor to
initialize those fields when an object is created, and two methods (`getName`
and `setAge`) to access and modify the object's data.
Classes and
methods are fundamental building blocks in Java and are used to create and
organize code in a structured and modular way. Classes define the structure of
objects, and methods define their behavior. This object-oriented approach is a
key feature of the Java programming language.
- Get link
- X
- Other Apps
Popular Posts
Artificial intelligence
- Get link
- X
- Other Apps
Datatype Programming in C, Data Type
- Get link
- X
- Other Apps
Computer Virus Describe in Hindi
- Get link
- X
- Other Apps
Getting Started C Programming
- Get link
- X
- Other Apps
In C, variable names must adhere to certain rules and conventions. Here are some examples of valid and invalid variable names and the reasons why:
- Get link
- X
- Other Apps
Decision Control Structure in C, Boolean Operator and Expression
- Get link
- X
- Other Apps
Operators and Expressions in C Programming
- Get link
- X
- Other Apps
Operators in Java
- Get link
- X
- Other Apps
Comments
Post a Comment