2

It seems very silly, but I am really confused. Please see below code:

package com.one;
public class SuperClass {
    protected void fun() {
        System.out.println("base fun");
    }
}
----
package com.two;
import com.one.SuperClass;
public class SubClass extends SuperClass{
    public void foo() {
        SuperClass s = new SuperClass();
        s.fun(); // Error Msg: Change visibility of fun() to public 
    }
}

I have read from oracle doc and here as well, that protected members are visible in the sub class in another package also. So fun() should be visible in SubClass in package two. Then why the error?

Am I terribly missing something very obvious?

Dexter
  • 4,036
  • 3
  • 47
  • 55
  • 5
    The method is visible to the instance of `SubClass` itself. So you can call `this.fun()`. But if you create a different instance and try to call its method it won't allow since the instance of `SubClass` has nothing to do with **that** instance of `SuperClass`. – Zabuzard Dec 13 '17 at 18:50
  • 2
    "Visible" does not give you a full picture. You can invoke the method on itself, i.e. `this.fun()` or simply `fun()`, but when you create a new instance of `SuperClass` the method is off-limits, because `SubClass` becomes a "regular" client of `SuperClass` despite also inheriting from it. – Sergey Kalinichenko Dec 13 '17 at 18:52

2 Answers2

3

The Java Language Specification says

A protected member or constructor of an object may be accessed from outside the package in which it is declared only by code that is responsible for the implementation of that object.

What that means is that if you're writing a subclass outside the package of the original class, each object can call the superclass's protected methods on itself, but not on other objects.

In your example, because s is a different object from this, you can't call s.fun(). But the object would be able to call the fun method on itself - with this.fun() or just fun().

Dawood ibn Kareem
  • 77,785
  • 15
  • 98
  • 110
0

Protected methods are only visible to subclasses from the inside. If you create a new instance of SuperClass, you are accessing it from the outside.

Nate
  • 481
  • 3
  • 11