Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

to be more public

 
Robertovich Wartins
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You cannot override private method..
It is because of the private method's accessibility..
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24208
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic