Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Inheritance output is unexpected

class Parent
{
    private void method1()
    {
        System.out.println("Parent's method1()");
    }
    public void method2()
    {
        System.out.println("Parent's method2()");
        method1();
    }
}
class Child extends Parent
{
    public void method1()
    {
        System.out.println("Child's method1()");        
    }

    public static void main(String args[])
    {
        Child p = new Child();
        p.method2();
    }
}

ans is

Parent's method2()
Parent's method1()

If i am creating object of Child class then why output is of parent class method?? even method1 is private in parent. It shakes my all inheritence concept.

like image 649
ankita gahoi Avatar asked May 31 '13 11:05

ankita gahoi


3 Answers

It would call the child method if it overrode the parent method. But it doesn't, since the parent method is private, and thus can't be overridden.

When your intention is to override a method from a parent class or interface, you should always annotate the method with @Override. If you did, in this case, you would get an error from the compiler, since the child's method1 doesn't override any method.

When the parent class is compiled, the compiler looks for the method1 in the Parent class. It finds it, and sees that it's private. Since it's private, it knows that it's not overridable by any subclass, and thus statically binds the method call to the private method it has found.

If method1 was protected or public, the compiler would find the method, and know that the method could be overridden by a subclass. So it would not statically bind to the method. Instead, it would generate bytecode that would look for method1 in the concrete class, at runtime, and you would then get the behavior you expect.

Think about it: if a subclass could override a private method, the method wouldn't be private anymore.

like image 187
JB Nizet Avatar answered Nov 14 '22 09:11

JB Nizet


by default child class will be having access to parent method. you are calling p.method2()... which does not exist in Child class so it is executing from parent...

Though method1() is private is Parent.. it is getting called from the local method i.e. method2()... so method1() has got accessibility in method2()....

like image 22
Pavan Kumar K Avatar answered Nov 14 '22 09:11

Pavan Kumar K


Private members are not inherited by child classes. Therefore you are just defining a completely independent public void method1 in the subclass. Naturally, it does not participate in dynamic dispatch.

like image 1
Marko Topolnik Avatar answered Nov 14 '22 08:11

Marko Topolnik