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.
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.
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()....
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With