• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

public ...private....

 
amal shah
Ranch Hand
Posts: 92
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i came across the following question..

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[])
{
Parent p = new Child();
p.method2();
}
}

according to my knowledge the o/p should be

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

but the o/p is

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

and the explanation given for such a o/p is:

Explanation:
Because method1() of the Parent class is private, it will be invoked. Had method1() of the Parent class been public, protected, or friendly (default), the Child's method would have been called.

i am unable to understand....the explanation...pls help

thanking u
amal
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15216
36
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Private methods are private. They are only visible to the class in which they are declared. So your class Child doesn't know about the method1() in class Parent.

The method1() in class Child does not override the method in class Parent - it is just a completely new method.

So if you turn it around and look from the view of class Parent, the private method1() is not overridden by the method1() in class Child - so if you call method1() in class Parent, it just calls its own private method.

If you are using Java 5, you should always annotate methods that you intended as overridden versions of the super class with the @Override annotation. If you do that, the compiler will warn you for situations like this, where your method is not actually overriding a super class method:
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
With other words, private methods aren't polymorphic.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic