Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java protected methods access from different instance

I was extending a class from another package when I found something that wasn't compiling, even though I thought it should compile.

I have two classes, in different packages. In package com.foobar.a:

package com.foobar.a;

public class A {

    protected void foo1() {
        System.out.println("foo1() was called!");
    }

    protected static void foo2() {
        System.out.println("foo2() was called!");
    }

}

And in package com.foobar.b:

package com.foobar.b;

import com.foobar.a.A;

public class B extends A {

    public void bar() {
        A obj = new A();
        obj.foo1(); // This doesn't compile
        A.foo2(); // This does compile
    }

}

Now, according to this: http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html a subclass should be able to access the method, even if it's outside the same package (and we see that with the method being static it works). In fact, I am programming in Eclipse and the suggestion it's giving me to fix the issue is "change visibility of 'foo1()' to protected", but it's already protected.

So, what's exactly going on here? In the oracle specifications it indicates access level using Class, Package, Subclass and World. Should be add "Instance" to this list, and if so, which would the rules be?

like image 335
Noel De Martin Avatar asked Aug 09 '26 05:08

Noel De Martin


1 Answers

If you want to access this method in a subclass, you can use it like this:

public void bar() {
    this.foo1();
}

Creating an object and trying to access a protected method isn't like accessing a super class protected method.

like image 124
BobTheBuilder Avatar answered Aug 10 '26 18:08

BobTheBuilder