问题描述
在抽象类中,我必须将哪个访问修饰符用于方法,所以子类可以决定它是否应该公开?是否可以在 Java 中覆盖"修饰符?
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, ifsomeone 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.
这篇关于覆盖方法是否可以具有与基类中的访问说明符不同的访问说明符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!