-2

I have the following structure -

App.java -

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

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

AnimalApp.java -

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.

1
  • 1
    It's just animalName = "abc"; Why are you qualifying it with a class name? Commented Jan 18, 2022 at 23:09

1 Answer 1

2

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

1
  • @alex87 'just animalName, even if it's not the best way' - actually it's absolutely normal to use a property name alone when it doesn't clash with the name of the parameter Commented Jan 19, 2022 at 17:53

Not the answer you're looking for? Browse other questions tagged or ask your own question.