I have 3 classes where one is the super class
and other two are sub classes
. They have print()
method common in them. While calling print()
methods from main()
I have upcasted the objects to super class
then is it not that it must invoke method of super class
rather than subclasses
. I am confused here a little bit. How is it possible? Is there any reason for such kind of behaviour in java.
Here is my code
class Tree {
public void print() {
System.out.println("I am Tree");
}
public static void main(String []args) {
Tree t[] = new Tree[3];
t[0] = new Tree();
t[1] = new BanyanTree();
t[2] = new PeepalTree();
for(int i = 0; i < 3; i++) {
((Tree)t[i]).print();
}
}
}
public class BanyanTree extends Tree{
public void print() {
System.out.println("I am BanyanTree");
}
}
public class PeepalTree extends Tree{
public void print() {
System.out.println("I am PeepalTree");
}
}
The output of the program is
I am Tree
I am BanyanTree
I am PeepalTree
According to me the output should be
I am Tree
I am Tree
I am Tree
Am I missing something here???