So I'm reading an article on Polymorphism. I stumbled upon a word upcasting
. I kind a understand it.
In the same article we have an e.g
They say this is an e.g of upcasting. OK!!
class Bike{
void run(){System.out.println("running");}
}
class Splendor extends Bike{
void run(){System.out.println("running safely with 60km");}
public static void main(String args[]){
Bike b = new Splendor();//upcasting
b.run();
}
}
Now the same article has one more e.g following the above example
For this one they say "This example is also given in method overriding but there was no upcasting."
class Bank {
float getRateOfInterest() {
return 0;
}
}
class SBI extends Bank {
float getRateOfInterest() {
return 8.4 f;
}
}
class ICICI extends Bank {
float getRateOfInterest() {
return 7.3 f;
}
}
class AXIS extends Bank {
float getRateOfInterest() {
return 9.7 f;
}
}
class TestPolymorphism {
public static void main(String args[]) {
Bank b;
b = new SBI();
System.out.println("SBI Rate of Interest: " b.getRateOfInterest());
b = new ICICI();
System.out.println("ICICI Rate of Interest: " b.getRateOfInterest());
b = new AXIS();
System.out.println("AXIS Rate of Interest: " b.getRateOfInterest());
}
}
I don't get it why this e.g is not upcasting when it is very same to the previous e.g.
Can someone please clarify? I have linked the article above.
CodePudding user response:
I believe, you understood this correctly, that Parent reference holding a child object, is termed as Upcasting.
In the article, they mention the same example for Method Overriding topic (https://www.javatpoint.com/method-overriding-in-java) so my guess is that they are just stating that "This example has been used twice, first in method-overriding where they didn't talk about upcasting, and now in this topic"
CodePudding user response:
You have to look at the example mentioned. The code there does not make use of casting:
SBI s=new SBI();
ICICI i=new ICICI();
AXIS a=new AXIS();
System.out.println("SBI Rate of Interest: " s.getRateOfInterest());
System.out.println("ICICI Rate of Interest: " i.getRateOfInterest());
System.out.println("AXIS Rate of Interest: " a.getRateOfInterest());