Syntax-
return_type method_name(arg1,arg2,.....)
{
}
-
arguments arg1, arg2, arg3,.... are optional.
-
return_type is the data type of the variable returned by the method or it can be void if the method does not return anything.
-
Example
public class Test {
public static void main(String[] args) {
Test t = new Test();
t.add_nums(); // Call to the method
}
public void add_nums() {
int i = 10;
int j = 15;
int k = i + j;
System.out.println("k:" + k);
}
}
int add_nums()
{
int i=10;
int j=15;
int k=i+j;
return k;
}
int n= add_nums(); // Call to the method
System.out.println("n:" + n);
void add_nums(int i, int j)
{
int k=i+j;
System.out.println("k:" + k);
}
add_nums(10,15); // Call to the method
int add_nums(int i, int j)
{
int k=i+j;
return k;
}
int n= add_nums(10,15); // Call to the method
System.out.println("n:" + n);
- With method overloading, multiple methods can have the same name with different parameters.
Example-
void add_nums(); void add_nums(int i);
void add_nums(char i); // valid method
void add_nums(int i, int j); void add_nums(String i, int j);
// return type doesn’t play any role here **void add_nums(); and int add_nums(); will throw error. **
- Method overriding is used with classes when a child class has the same method as the parent class. Which means, overriding happens when a child class has its own implementation of a method which is also declared/implemented in the parent class.