Accessing a protected variable from a subclass outside package

You're attempting to use them as if they were public. They are not public, they are protected.

Example

ProVars p = new ProVars();
p.foo(); // This will throw an error because foo() is not public.

The correct usage, for a subclass to use a protected method or variable is:

public class MyClass extends ProVars
{
     public MyClass()
     {
           System.out.println(i); // I can access it like this.
           foo(); // And this.
     }
}

Why does this work?

Because you've inherited the class. That means you've got all of its methods and it's variables. Now, because your method and variable is protected, it also means that it can be accessed from the subclass. Try and declare them as private and see what happens.


Even inside a derived class, you can only access a protected field from a qualifier that is at least of your own type.

Inside AnotherClass, you can access new AnotherClass().i, but not new ProVars().i.


It would be fine if your main method wasn't static. Static methods don't care about inheritance hence your "extends ProVars" is not going to work. This on the other hand should work:

public class AnotherClass extends ProVars {

   public void accessProtected() {
       System.out.println(this.i);
       this.foo();
    }

    public static void main(String[] args) {
        AnotherClass p = new AnotherClass();
        p.accessProtected();
    }

}

Tags:

Java