Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Protected variable not accessible within child class in Java

I have the following structure –

App.java

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

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

AnimalApp.java

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

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

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"; below animalName there is a read line which reads –

The field AnimalApp.animalName is not visible

How can this be possible?

I am using VSCode on Ubuntu and OpenJDK 11.

>Solution :

That happens because you confusing static and instance members.

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading