Java - Protected field not accessible from the subclass? [duplicate]

三世轮回 提交于 2019-12-03 17:31:56

You can't access a protected superclass field in a different instance of the class.

There's a good reason: you don't know whether it has the same subclass as yourself, or a completely different subclass. If it were allowed to access the protected field, you would be allowed to access the internals of entirely unrelated classes.

If you are sure that the object is of the same subclass as the class that wants to access the superclass field, you can cast the object; when you that, you can access the protected field.

The rules are described in the Java Language Specification section 6.6.2

6.6.2. Details on protected Access

A protected member or constructor of an object may be accessed from outside the package in which it is declared only by code that is responsible for the implementation of that object.

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, 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. [This is the relevant section]

protected variables are accessible outside class, but only through inheritance. So, if you change that statement to this:

public Robot(){

    Machine mach1 = new Machine();
    String name = mach1.name;
    // This will work (access on `this` reference)
    String description = this.description; 
}

Actually protected modifier means that, the field is visible to be inherited by the subclasses, and it can be used only there, using this reference.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!