Possible Duplicate:
Why can't you reduce the visibility of a method in a java subclass?
How come I can override a private
method in superclass with a public
when in a subclass, but I cannot override a public
method in the superclass into private
method in subclass?
Why?
Thank you in advance.
Overriding a method can't ever reduce the visibility. Allowing that would violate the Liskov Substitution Principle, which states (simplified) that all objects of a derived class B
must have the same properties as the base class A
. In this case one such "property" would be a public method foo
which would be "lost" if B
had that same method, but made it protected
.
Also, since private
methods are not inherited (try calling it from a derived class!) they can't ever be overriden. You can have a public
method with the same name as a private
one in the base class, but that's not overriding, it's simply a new method with the same name, but not other relation. Calls to the private
method in the base class will not call the public
method in the superclass, even when executed on objects of the superclass!
In other words: private
methods never use runtime polymorphism.
See this sample:
public static class Base {
public void callBoth() {
foo();
bar();
}
private void foo() {
System.out.println("Base.foo");
}
protected void bar() {
System.out.println("Base.bar");
}
}
public static class Sub extends Base {
public void foo() {
System.out.println("Sub.foo");
}
public void bar() {
System.out.println("Sub.bar");
}
}
When executing new Sub().callBoth()
the output will be this:
Base.foo Sub.bar
Because it doesn't break the class contract to make a method more available. If Kitten subclasses Animal, and Animal has a public method feed(), then Kitten must also have a public method feed(), as it must be possible to treat any instance of Kitten like an instance of Animal. Redefining the access level to private would break that.
If the public method became private, then it would not be possible to up cast the instance into its parent class (because one of the methods would be unavailable).
If the private method became public, then it would be possible to up case the instance into its parent class (because then you would just have no way to grab the private / publicly overriden method).
The access level can't be more restrictive than the overridden method.
private-->[default]-->protected-->public
By overriding you're saying that your subclass can be called with the same api but may function differently. Making something public increases the access level - so you're not removing guaranteed functionality.
By making a public method private (if you could actually do this) you'd be removing functionality, so breaking the "contract". It also doesn't make sense in that the method could still be called publicly, it's just that the public call would access the public method in the superclass, which would be counterintuitive.
精彩评论