简体   繁体   English

受保护的变量在 Java 中的子 class 内不可访问

[英]Protected variable not accessible within child class in Java

I have the following structure -我有以下结构 -

App.java - App.java -

package JohnParcellJavaBasics.AccessModifierDemo;
import JohnParcellJavaBasics.AccessModifierDemo.*;

public class App {
    public static void main(String[] args) {
        
    }
}

AnimalApp.java - AnimalApp.java -

package JohnParcellJavaBasics.AccessModifierDemo.Animal;
import JohnParcellJavaBasics.AccessModifierDemo.Animal.*;

public class AnimalApp {
    protected String animalName;
    public void myMethod() {
        
    }
}

Eagle.java - Eagle.java -

package JohnParcellJavaBasics.AccessModifierDemo.Animal.Bird;
import JohnParcellJavaBasics.AccessModifierDemo.Animal.*;

public class Eagle extends AnimalApp {
    public void myMethod() {
        AnimalApp.animalName = "abc";
    }
}

In the file - Eagle.java , in the line AnimalApp.animalName = "abc";在文件 - Eagle.java中,在AnimalApp.animalName = "abc"; below animalName there is a read line which reads -animalName下方有一条读取行,内容为-

The field AnimalApp.animalName is not visible

How can this be possible?这怎么可能?

I am using VSCode on Ubuntu and OpenJDK 11.我在 Ubuntu 和 OpenJDK 11 上使用 VSCode。

That happens because you confusing static and instance members.发生这种情况是因为您混淆了 static 和实例成员。

AnimalApp.animalName - is a way to refer to a static variable (by using the class name, because static variable resides on the class, they do not belong to any instance of the class and hence cant be inherited). AnimalApp.animalName - is a way to refer to a static variable (by using the class name, because static variable resides on the class, they do not belong to any instance of the class and hence cant be inherited).

this.animalName or super.animalName or simply animalName - are proper ways to access instance variables this.animalNamesuper.animalName或只是animalName - 是访问实例变量的正确方法

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

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