I am learning JAVA from Core Java An Integrated Approach
by Dr.R.Nageswara Rao.
The book mentions that Method Overloading and Method overriding both are types of Dynamic Polymorphism. But after referring to the online blogs and websites I have found that Method Overloading is Static and Method Overriding is Dynamic polymorphism. I am not sure which one to follow.
Explanation from the book:
Method Overloading
public class Sample {
void add(int a, int b){
System.out.println("Sum of Two: "+ (a+b));
}
void add(int a, int b, int c){
System.out.println("Sum of Two: "+ (a+b+c));
}
}
The above class has two methods. The question is who will decide which method to call? Is it Java compiler or JVM? Because the methods are called by using an object, the compiler can not decide at the time of compilation which method is actually called by the user. It has to wait till the object is created for the Sample class. And the creation of an object takes place at runtime by JVM. Now, JVM should decide which methods actually called by the user at runtime. Hence its dynamic polymorphism.
Method Overriding
Here also JVM decides which method is called depending on the data type(class) of the object used to call the method. Hence method overriding is also a type of Dynamic Polymorphism.
Note:
Method overloading and method overriding using static methods, private methods, and final methods are examples of static polymorphism.
Method overriding is dynamic, because the decision on which method to call occurs at runtime. method overloading is static, because the decision is made at compile type, based on the number and types of the parameters.
Overriding:
public class A {
public void foo(){System.out.println("I am A");}
}
public class B extends A {
public void foo(){System.out.println("I am B");}
}
A z = getAnObject();
z.foo();
Let's say that getAnObject()
returns an Object of type A
, but the compiler has no way to tell if its runtime class is A
or B
or something else. Indeed, in different invocations, the returned object may be of different types. If it happens that its type is B
, the above will print "I am B".
public class A {
public void foo(int x){System.out.println("with int param");}
public void foo(String x){System.out.println("with String param");}
}
A a = new A();
a.foo(42);
That prints "with int param". The compiler knows that the param is an int
, not a String
, so it knows at compile-time which foo()
to use.