3

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?

1
  • If you will try to access foo1() directly, instead of using it as obj.foo1() , then it will work. Commented May 14, 2013 at 10:32

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

this.foo1(); will work but not obj.foo1();. obj.foo1(); is not visible inside class B. The only foo1() visible is the one which is inherited which is actually this.foo1(). What is wrong over here is that you are creating an object of A and trying to invoke its foo1().This is the intended behaviour, protected means that the inherited classes and same package classes can see the method.

2 Comments

If that was the case, then even A.foo2() should had generated an error, since the access specifiers of foo2() and foo1() are the same, the only difference being that foo2() is static
the only difference being that foo2() is static ==> That is the difference !!!! foo2(); or A.foo2() refers to the same method, obj.foo1() and this.foo1() are different calls altogether !!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.