Saturday, 31 August 2013

Unexpected output in Java - Inheritance related

Unexpected output in Java - Inheritance related

This is my sample program.
class parent
{
void display(int i)
{
System.out.println("parent");
}
}
class child extends parent
{
void display(byte i) //Line 0
{
System.out.println("child");
return;
}
}
class impl
{
public static void main(String...args)
{
parent p = new parent();
p.display(5); //Line 1
child c = new child();
c.display(3); //Line 2
}
}
This is my output.
varun@\:~/Desktop/JavaFiles$ java impl
parent
parent
I understand Line 1 calls the display() method from the parent and outputs
"parent" which is expected.
But I don't understand why Line 2 calls the display() from the parent
instead of the child even though I am not using polymorphic initialization
(just a regular initialization of the child class is what I did).

No comments:

Post a Comment