为什么 Java 允许增加子类中受保护方法的可见性? [英] Why Java allows increasing the visibility of protected methods in child class?

查看:19
本文介绍了为什么 Java 允许增加子类中受保护方法的可见性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

abstract class Base{
      protected abstract void a();
}

class Child extends Base{
      @Override
      public void a(){
          //why is this valid
      }
}

为什么我们不能降低能见度但可以增加能见度?

Why is that we can't reduce the visibility but can increase it?

我还需要实现模板模式,其中可见的公共方法只能是基类.

Also I need to implement Template pattern in which the public methods visible can only be of base class.

示例:

abstract class Base{
      public void callA(){
      //do some important stuff
      a();
      }

      protected abstract void a();
}

class Child extends Base{
      @Override
      public void a(){
          //why is this valid
      }
}

现在如果java允许增加可见性,那么有两种公开可见的方法??

Now if java allows to increase visibility then there are two methods visible publicly??

我知道接口是一种解决方案,但还有其他出路吗???

I know interface is one solution but is there some other way out???

推荐答案

为什么不允许降低可见性在其他回复中已经解释过(这会违反父类的约定).

Why decreasing visibility is not allowed is already explained in other responses (it would break the contract of the parent class).

但是为什么允许增加方法的可见性呢?首先,它不会破坏任何合同,因此没有理由不允许.有时,当在子类中对不受保护的方法有意义时,它会很方便.

But why it is allowed to increase the visibility of a method? First, it would not break any contract, so there is no reason to not allow it. It can be handy sometimes, when it makes sense in the child class for a method to not be protected.

其次,不允许它会产生副作用,有时无法同时扩展类和实现接口:

Second, not allowing it could have the side effect of making impossible sometimes to extend a class and implement an interface at the same time:

interface Interface1 {
   public void method();
}

public class Parent {
   protected abstract void method();
}

public class Child extends Parent implements Interface1 {
   @Override
   public void method() {
   }
   //This would be impossible if the visibility of method() in class Parent could not be increased.
}

关于你的第二个问题,你无能为力.你必须相信实现子类的人不会做任何破坏你实现的事情.即使 java 不允许增加可见性,这仍然不能解决您的问题,因为可以创建具有不同名称的公共方法来调用抽象方法:

About your second question, you can do nothing about it. You have to trust that the person who implements the child class doesn't do anything that breaks your implementation. Even if java wouldn't allow to increase visibility, that would still not fix your problem, because a public method with a different name could be created that calls the abstract method:

class Child extends Base{
      @Override
      protected void a(){

      }

      public void a2() {
           a(); //This would have the same problems that allowing to increase the visibility.
      }
}

这篇关于为什么 Java 允许增加子类中受保护方法的可见性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆