aspose file tools*
The moose likes Java in General and the fly likes to be more public Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "to be more public" Watch "to be more public" New topic
Author

to be more public

Robertovich Wartins
Greenhorn

Joined: Nov 21, 2006
Posts: 16
Question -
Methods may be overridden to be more public, not more private!
So why this is not working -

class PrivateOverride {
private void f() {
System.out.println("private f()");
}
}

class Derived extends PrivateOverride {
public void f() {
System.out.println("public f()");
}
}

public class Tests2 {
public static void main(String[] args) {
PrivateOverride po = new Derived();
po.f();
}
}
Ricky Martaputra
Ranch Hand

Joined: Apr 04, 2005
Posts: 42
You cannot override private method..
It is because of the private method's accessibility..
Peter Chase
Ranch Hand

Joined: Oct 30, 2001
Posts: 1970
If a subclass has a method of the same signature as a private method of the superclass, there is no relation between these two methods.

If you're coming from C++, this may be a surprise. I can't remember exactly how it is in C++, but I seem to remember it's different.


Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24184
    
  34

Well... you can define a method in Derived which looks as though it would override the method in PrivateOverride; but it won't be a polymorphic method. If you do something like this inside the class PrivateOverride:

PrivateOverride po = new Derived();
po.f();

you'll see it print "private f()", so your "override" really isn't an override.

But that wasn't really what you were asking. You were asking why the last class won't compile, right? The compiler decides the accessibility ("public-ness") of a method based on the compile-time type of the variable you're calling the method with. In other words, the fact that Derived has a public method called f() isn't even considered; all the compiler knows is that the variable is of type "PrivateOverride," and this class has no accessible method of that name.

You can only call Derived.f() through a variable of type "Derived".

So, now you're wondering why it matters that you can make a method "more public" if you can't then call the method? Honestly, it's not really useful that often. One case where it's used is to make Object.clone() public in a Cloneable object. You override the method to be public, and call super.clone() to invoke the Object version. Not very elegant, but as I said, this feature isn't really all that useful.


[Jess in Action][AskingGoodQuestions]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: to be more public