Could someone please explain why this happening:
class Apple {
String type;
setType(){
System.out.println("inside apple class");
this.type = "apple";
}
}
class RedApple extends Apple {
String type;
setType() {
System.out.println("inside red-apple class");
this.type = "redapple";
}
}
int main {
RedApple red = new RedApple();
Apple apple = (Apple) red;
apple.setType();
}
But the output produced is:
"inside red-apple class”
Why does the .setType()
method execute the sub-class method, and not the super-class method, even though I am up-casting, as can be seen?
That's because that's how polymorphism works in Java: it always uses the most-derived version of the method, which overrides other versions. The only way to get the base-class version is to use super.setType
within the most-derived override.
It's a basic feature of any OOP language. That's why all deconstructors in C++ should be virtual - to implement polymorphism. To make the appropriate method be called. This is a good artical to understand how it works
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With