File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes public ...private.... Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "public ...private...." Watch "public ...private...." New topic

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()");


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

public static void main(String args[])
Parent p = new Child();

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:

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
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 15081

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 8 API documentation
Ilja Preuss

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
I agree. Here's the link:
subject: public ...private....
It's not a secret anymore!