Methods in java
A Java method is a collection of statements that are grouped together to perform an operation. When you call the System.out.println method, for example, the system actually executes several statements in order to display a message on the console.
Now you will learn how to create your own methods with or without return values, invoke a method with or without parameters, overload methods using the same names, and apply method abstraction in the program design.
Declaration of methods
access_modifier return_type name_of_method(parameter List)
{
//method body
}
Method Overloading
Method Overloading:-If a class have multiple methods by same name but different parameters, it is known as Method Overloading.
Method overloading can be done by two ways:-
- By changing number of arguments
class Calculation{
void sum(int a,int b){System.out.println(a+b);}
void sum(int a,int b,int c){System.out.println(a+b+c);}
public static void main(String args[]){
Calculation obj=new Calculation();
obj.sum(10,10,10);
obj.sum(20,20);
}
}
output: 30
40
- By changing data type
class Calculation2{
void sum(int a,int b){System.out.println(a+b);}
void sum(double a,double b){System.out.println(a+b);}
public static void main(String args[]){
Calculation2 obj=new Calculation2();
obj.sum(10.5,10.5);
obj.sum(20,20);
}
}
output:21
40
Note: Method overloading is not possible by changing return type because they may cause ambiguity.
Can we overload main method() ?
Ans:- Yes, main method can be overloaded. You can any number of main() methods in a class by method overloading.
Example:-
class Overloading1{
public static void main(int a){
System.out.println(a);
}
public static void main(String args[]){
System.out.println("main() method invoked");
main(10);
}
}
output: main() method invoked
10
No comments:
Post a Comment