Im currently learning java and couldn't understand this topic. referencing sub class objects with super class. After going through multiple websites and posts, my confusion has just increased. Example code:
public abstract class Bird {
private void fly() {
System.out.println("Bird is flying");
}
public static void main(String[] args) {
Bird bird = new Pelican();
bird.fly();
}
}
class Pelican extends Bird {
protected void fly() {
System.out.println("Pelican is flying");
}
}
The output is Bird is flying - why?
Also I have 3 questions:
Bird bird = new Pelican();
In the above part, what can I use in place of Bird type (if there are more classes extending Bird)? I'm preparing for the OCA 1 exam and the questions on this topic are confusing me a lot.
What methods and variables are output when using these references? In the above example, pelican object is created but fly method that runs is bird?
If Casting is done, what types I can use and what types I cant?
There are multiple questions about this on stackoverflow and other java websites but multiple sources,multiple answers are confusing to me. I understand time is valuable but can someone please clear this doubt once and for all for me?
Thanks in advance.
In order for you to call the method from subclass you have to use method overriding which is also known as runtime polymorphism. As the object that you have declared is Bird and it has a private method of fly which cant be overriden, your output will be "Bird is flying".
However if you were to initialize it as
Pelican pelican = new Pelican();
then the output would be "Pelican is flying"
You can read more about it here https://www.geeksforgeeks.org/dynamic-method-dispatch-runtime-polymorphism-java/