-3
public SuperClass{
    protected int a1;
}

// Consider that two classes are in different package.
public SubClass extends SuperClass{
    void m1(){
        SuperClass sp = new SuperClass();
        sp.a1 = 1; // Error: Subclass.a1 is not visible
    }
}

I think that protected member a1 is visible to SubClass. In addition, field a1 belongs to SuperClass. So why it's not visible?

  • 5
    It's only visible in the subclass through an instance of the subclass type. You can't do `superClassObject.protectedMember`, it has to be `subclassObject.superclassProtectedmember` within the subclass. – ernest_k Apr 17 '20 at 11:19
  • but a1 belongs to SuperClass. So why a1 is not visible to sp object? – Hoang Nhat Minh Apr 17 '20 at 11:24
  • The answer on this question explains it best: https://stackoverflow.com/questions/18573016/understanding-javas-protected-modifier – ernest_k Apr 17 '20 at 11:33

1 Answers1

0

You are instantiating a object of SuperClass. Then trying to access protected member of SuperClass. Evnethough it is inside SubClass, this is basically an instance trying to access protected member. Try this.a1 instead.

Kshitij Dhakal
  • 816
  • 12
  • 24