Reputation: 115
class Bank{
float getRateOfInterest(){return 0;}
}
class SBI extends Bank{
float getRateOfInterest(){return 8.4f;}
}
class TestPolymorphism{
public static void main(String args[]){
Bank a = new SBI();
SBI b = new SBI();
a.getRateOfInterest();
b.getRateOfInterest();
}
}
a.getRateOfInterest()
and b.getRateOfInterest()
both gives same output. So what is the difference between both the statements?
I think 1st is upcasting.
Upvotes: 0
Views: 60
Reputation: 6425
All java method is virtual (by design).
They rely on the implementing classes to provide the method implementations.
Here is more information.
- Can you write virtual functions / methods in Java?
- https://en.wikipedia.org/wiki/Virtual_function
Here is an excerpt from wikipedia :-
public class Animal {
public void eat() {
System.out.println("I eat like a generic Animal.");
}
public static void main(String[] args) {
Animal animal=new Wolf ();
animal.eat(); //print "I eat like a wolf!
}
}
class Wolf extends Animal {
@Override
public void eat() {
System.out.println("I eat like a wolf!");
}
}
Virtual functions are resolved 'late'. If the function in question is 'virtual' in the base class, the most-derived class's implementation of the function is called according to the actual type of the object referred to, regardless of the declared type of the pointer or reference. If it is not 'virtual', the method is resolved 'early' and the function called is selected according to the declared type of the pointer or reference.
Virtual functions allow a program to call methods that don't necessarily even exist at the moment the code is compiled.
Upvotes: 0
Reputation: 186
It's not, if you construct it with new SBI()
. It'll always return 8.4f.
Upvotes: 0
Reputation: 12450
Java methods are all virtual, so the method called depends on the run-time type of the called object, not on the compile-time type of the variable holding the reference.
Upvotes: 1