Java – a protected member accessed in a derived class using a base class instance

I created an instance of the base class in a derived class and tried to access protected members

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

Base class:

package com.core;

public class MyCollection {

      protected Integer intg;
}

Derived classes in the same package –

package com.core;

public class MyCollection3 extends MyCollection { 

 public void test(){

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

Derived classes in different packages –

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
 }
}

When a derived class is also in the same package, but when a derived class is in a different package, how do you use a base class instance to access the protected members of the base class in the derived class?

If I mark protected members as "static", I can access protected members of the base class using base class instances in derived classes residing in different packages

Solution

It's right that you can't do that You cannot access this field because you are not in the same package as the class and do not access inherited members of the same class

The last point is the key point - if you write it

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

This will then work because you are changing the protected members of your own class (existing in that class through inheritance) However, in your case, you try to change the protected members of other classes in different packages Therefore, it is not surprising if you are denied access

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>