繁体   English   中英

限制子类访问父类方法

[英]Restricting child class from accessing parent class method

说我有一个接口I以及类A和B。

interface I
{
  method();
}

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

class B extends A
{
  method()
  { //Implementation 2
  }
}

我想限制B访问“方法”。 调用b.method()时应始终使用a.method()而不是b.method实现,其中a和b分别是A和B的实例。 有什么解决方法吗?

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

正如Stealthjong在他们的评论中提到的那样,您可以通过将Amethod() final

interface I {
    public void method();
}

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

class B extends A { }

因为Afinal修饰符应用于method()的实现,所以B无法重新定义它,而将始终调用它从A继承的版本。

如果我要写:

B instance = new B();
instance.method();

我将看到输出"Hello World!"

您可以这样实现B:

class B extends A
{
  method()
  {
    method(true);
  }

  method(boolean callSuper)
  {
    if (callSuper)
    {
      super.method();
    } else {
      method_impl();
  }

  method_impl()
  {
    //Implementation method of B class
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM