java - 谁能解释一下这里发生了什么 : "protected" modifier in java

标签 java inheritance protected

我学到的一件事是 private 在 java 中与在 C++ 中的意思并不相同。 java中的private是基于类的,而不是基于对象的。 即我可以使用“对象点符号”直接访问另一个对象私有(private)成员前提是我在该对象的类中这样做。

但是,protected 就不是那么清楚了。 我们必须在这里考虑两个包:pack1pack2
我们在pack1
中声明类AlphaBeta 并声明从 pack1 扩展 AlphaAlphaSub 和从 Alpha 扩展的 Gamma pack2 包中。 !

enter image description here

这是类代码,我在这里只包含与问题相关的类:AlphaAlphaSubGamma

package pack1;

public class Alpha{
  private int alphaPrivate;
  public int alphaPublic;
  protected int alphaProtected;
  int alphaPP;

  protected int alphaProtected(){
    return 1;
  }
  private int alphaPrivate(){
    return 1;
  }
}

package pack2;

import pack1.Alpha;
public class AlphaSub extends Alpha{
    int alphasubPP;
    private int alphasubPrivate;
    protected int alphasubProtected;
    public int alphasubPublic;

    public void meth() throws CloneNotSupportedException{
        new AlphaSub().alphaProtected(); //OK
        new Gamma().alphaProtected(); /*COMPILE ERROR. */

    }
}

很明显,即使 AlphaSub 和 Gamma 都从 Alpha 继承了 alphaProtected() ,也不能调用 Gamma 从 AlphaSub 继承的 alphaProtected() 。 . 如果这种情况是一个类的 protected 方法只能从该类内部调用,则不会调用 clone [由 Object 类的每个类继承]另一个类不可能吗??

有人可以澄清一下吗?

最佳答案

JLS 6.6.2.1. 中涵盖了您所经历的内容:

6.6.2.1. Access to a protected Member

Let C be the class in which a protected member is declared. Access is permitted only within the body of a subclass S of C.

In addition, if Id denotes an instance field or instance method, then:

  • If the access is by a qualified name Q.Id or a method reference expression Q :: Id (§15.13), where Q is an ExpressionName, then the access is permitted if and only if the type of the expression Q is S or a subclass of S.

  • If the access is by a field access expression E.Id, or a method invocation expression E.Id(...), or a method reference expression E :: Id, where E is a Primary expression (§15.8), then the access is permitted if and only if the type of E is S or a subclass of S.

  • If the access is by a method reference expression T :: Id, where T is a ReferenceType, then the access is permitted if and only if the type T is S or a subclass of S.

你是对的,如果你用 new Gamma().clone(); 替换 new Gamma().alphaProtected();,你会得到同样的编译错误。

关于java - 谁能解释一下这里发生了什么 : "protected" modifier in java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28565464/

相关文章:

java.lang.NoSuchMethodError : No static method isCtrlPressed(Landroid/view/KeyEvent;)

java - 如何在 Java 中的 Excel 工作簿之间复制工作表

c++ - 从派生类初始化列表调用基类构造函数的顺序

java - 为什么我允许 "direct access"到对象的 protected 字段,该对象的类是在不同的包中定义的?

java - 测试Java Web应用程序库的依赖关系

java - characteristic.getDescriptor() 返回 null

java - 在基类中访问派生类的属性

java - 具有类和子类空错误的数组

c# - 在 type.GetProperties() 时过滤掉 protected setter

java - 与 java 中的私有(private)/ protected 方法相关的性能与设计