| Author |
public ...private....
|
amal shah
Ranch Hand
Joined: May 05, 2006
Posts: 92
|
|
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
Bartender
Joined: Aug 16, 2005
Posts: 12929
|
|
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:
|
Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
|
 |
Ilja Preuss
author
Sheriff
Joined: Jul 11, 2001
Posts: 14112
|
|
|
With other words, private methods aren't polymorphic.
|
The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
|
 |
 |
|
|
subject: public ...private....
|
|
|