覆盖方法可以具有与基类中不同的访问说明符吗? [英] Can an overriding method have a different access specifier from that in the base class?
问题描述
在抽象类中,哪个访问修饰符必须用于
方法,以便子类可以决定是否应将其公开?
Which access modifier, in an abstract class, do I have to use for a method, so the subclasses can decide whether it should be public or not? Is it possible to "override" a modifier in Java or not?
public abstract class A {
??? void method();
}
public class B extends A {
@Override
public void method(){
// TODO
}
}
public class C extends B {
@Override
private void method(){
// TODO
}
}
我知道,如果有人呼叫
,静态绑定会出现问题:
I know that there will be a problem with static binding, if someone calls:
// Will work
A foo = new B()
foo.method();
// Compiler ?
A foo = new C();
foo.method();
但是也许还有另一种方法。我该如何实现?
But maybe there is another way. How I can achieve that?
推荐答案
可以放松限制,但不能使其更加严格:
It is possible to relax the restriction, but not to make it more restrictive:
public abstract class A {
protected void method();
}
public class B extends A {
@Override
public void method(){ // OK
}
}
public class C extends A {
@Override
private void method(){ // not allowed
}
}
使用原始方法 private
也不起作用,因为这种方法不是在子类中可见,因此不能被覆盖。
Making the original method private
won't work either, since such method isn't visible in subclasses and therefore cannot be overriden.
我建议使用 interface
s选择性地公开或隐藏方法:
I would recommend using interface
s to selectively expose or hide the method:
public interface WithMethod {
// other methods
void method();
}
public interface WithoutMethod {
// other methods
// no 'method()'
}
public abstract class A {
protected void method();
}
public class B extends A implements WithMethod {
@Override
public void method(){
//TODO
}
}
public class C extends B implements WithoutMethod {
// no 'method()'
}
...然后只能通过接口使用实例。
... then only work with the instances through the interfaces.
这篇关于覆盖方法可以具有与基类中不同的访问说明符吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!