Search code examples
javaprotectedaccess-control

java - protected members accessed in derived class using base class instance


I created instance of base class in derived class and tried to access protected members.

I can directly access protected members in a derived class without instantiating the base class.

Base class:

package com.core;

public class MyCollection {

      protected Integer intg;
}

A derived class in the same package -

package com.core;

public class MyCollection3 extends MyCollection { 

 public void test(){

  MyCollection mc = new MyCollection();
  mc.intg=1; // Works
 }
}

A derived class in a different package -

package secondary;

import com.core.MyCollection;

public class MyCollection2 extends MyCollection{ 

 public void test(){
  MyCollection mc = new MyCollection();
  mc.intg = 1; //!!! compile time error - change visibility of "intg" to protected
 }
}

How it is possible to access a protected member of a base class in a derived class using instance of base class when derived class is also in same package but not when derived class is in different package?

If I mark protected member as "static" then I am able to access protected member of base class using instance of base class in a derived class which resides in a different package.


Solution

  • You're right that you can't do this. The reason why you can't access the field, is that you're not in the same package as the class, nor are you accessing an inherited member of the same class.

    The last point is the critical one - if you'd written

    MyCollection2 mc = new MyCollection2();
    mc.intg = 1;
    

    then this would work, as you're changing a protected member of your own class (which is present in that class through inheritance). However, in your case you're trying to change a protected member of a different class in a different package. Thus it should come as no surprise that you're denied access.