a874 a874 - 4 months ago 9
Java Question

Why the output of this java code related to polymorphism is this?

I came across this code.

class Id
{
public static void main(String s[])
{
Id obj=new Idd();
obj.disp();
}
private void disp()
{
System.out.println("disp of parent");
}
}
class Idd extends Id
{
public void disp()
{
System.out.println("disp of child");
}
}


The output of this code is
disp of parent
. I know that
private
method can't be inherited in java. So at the time of function call
obj.disp()
,compilation error should have come.

But the code successfully compiles and prints
disp of parent
. I am unable to understand why ?

Answer

There are two parts to this:

  1. Why did it compile?

  2. Why does it call the parent class's private disp (Id#disp) instead of the child class's public disp (Idd#disp)?

It compiled because the main function is part of the Id class, and so has access to all of the private parts of Id, including Id#disp.

It called Id#disp (the parent one) because as you said, private methods are not inherited. Polymorphism doesn't apply to them. If it did, it would be impossible for a class to have any private members. So the compiler sees obj.disp, knows that obj is typed as Id, and knows that disp is a private method of Id — so it wires it up directly, without considering any method with a matching signature on the object iself defined by a subclass. Idd#disp is not an override of Id#disp, they're entirely separate methods.