There are two ways to overload the method in java
class Adder{
static int add(int a,int b){return a+b;} // 2 arguments
static int add(int a,int b,int c){return a+b+c;} //3 arguments
}
class TestOverloading1{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}}
In the above example, we have created two methods, first add() method performs addition of two numbers and second add method performs addition of three numbers.
In the above example, we are creating static methods so that we don't need to create instance for calling methods.
class Adder{
static int add(int a, int b){return a+b;} // 2 arguments of int data type
static double add(double a, double b){return a+b;} // 2 arguments of double data type
}
class TestOverloading2{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}}
In the above example, we have created two methods that differs in data type. The first add method receives two integer arguments and second add method receives two double arguments.
Note : Method overloading is not possible by changing the return type of the method.
class TestOverloading4{
public static void main(String[] args){System.out.println("main with String[]");}
public static void main(String args){System.out.println("main with String");}
public static void main(){System.out.println("main without args");}
}
Yes, by method overloading. You can have any number of main methods in a class by method overloading. But JVM calls main() method which receives string array as arguments only.
class ABC{
//Overridden method
public void disp()
{
System.out.println("disp() method of parent class");
}
}
class Demo extends ABC{
//Overriding method
public void disp(){
System.out.println("disp() method of Child class");
}
public void newMethod(){
System.out.println("new method of child class");
}
public static void main( String args[]) {
ABC obj = new ABC();
obj.disp();
ABC obj2 = new Demo(); // Covariance with reference types
obj2.disp();
}
}
In the above example, we have defined the disp() method in the subclass as defined in the parent class but it has some specific implementation. The name and parameter list of the methods are the same, and there is IS-A relationship between the classes.
No, a static method cannot be overridden. It can be proved by runtime polymorphism, so we will learn it later.
It is because the static method is bound with class whereas instance method is bound with an object. Static belongs to the class area, and an instance belongs to the heap area.
Method Overloading :
Method Overriding :
Consider a scenario where Bank is a class that provides functionality to get the rate of interest. However, the rate of interest varies according to banks. For example, SBI, ICICI and AXIS banks could provide 8%, 7%, and 9% rate of interest.
Go ahead and code the above scenario.