Reputation: 1092
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???
Upvotes: 2
Views: 463
Reputation: 1
base class work as blueprint for derived class, since derived class inherit from base class and adds its own behaviors , the following link maybe help for this topic.
Upvotes: 0
Reputation: 1
If DerivedClass
extends BaseClass
and has a method with same name and same signature of BaseClass
then the overriding will take place at run-time polymorphism.
Also there is no need in upcast as you already initialized your array as BaseClass[ ]
Upvotes: 0
Reputation: 376
This is called polymorphism. The method takes the same type (none), same return type (void), and same name (print). So, when you call the print method, it calls the most specialized (the method that is lowest in the inheritance tree). There is something called what they think the object is and what it really is. They think it is a Tree, but is actually a Banyan Tree. If you up cast it, it doesn't do anything because the array of Trees make it so that they think they are Trees, and if you up cast it to a tree they still think it is a tree. Technically, you're up casting it to the exact same thing. Sorry for not including this in my answer. When you make a new Tree, the inheritance structure looks like this.
Object (Cosmic Super-class)
|
\ /
Tree
The most specialized method is tree. However, when you create another type of tree, let's say BanyanTree, the structure looks like this.
Object
|
\ /
Tree
|
\ /
BanyanTree
The most specialized print method comes from BanyanTree, so it executes that. Sorry if you didn't understand, it's a pretty complicated topic.
Upvotes: 1