限制子类访问父类方法

bin*_*bin 2 java oop interface protected

假设我有一个接口I和A和B类.

interface I
{
  method();
}

class A implements I
{
  method()
  { //Implementation 1
  }
}

class B extends A
{
  method()
  { //Implementation 2
  }
}
Run Code Online (Sandbox Code Playgroud)

我想限制B访问'方法'.对b.method()的调用应始终使用a.method()而不是b.method实现,其中a和b分别是A和B的实例.有没有解决方法?

希望接口支持另一个访问修饰符来处理这种情况.

Jon*_*onK 6

正如stealthjong在评论中提到的那样,你可以通过以下方式A实现method() final:

interface I {
    public void method();
}

class A implements I {
    public final void method() {
        System.out.println("Hello World!");
    }
}

class B extends A { }
Run Code Online (Sandbox Code Playgroud)

因为Afinal修饰符应用于实现method(),B然后无法重新定义它,而是始终调用它继承的版本A.

如果我写:

B instance = new B();
instance.method();
Run Code Online (Sandbox Code Playgroud)

我会看到输出"Hello World!".