问题描述
我在派生类中创建了基类的实例,并尝试访问受保护的成员。
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.
基类:
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.
推荐答案
你是对的,你不能这样做。您无法访问该字段的原因是您与该类不在同一个包中,您也无法访问同一类的继承成员。
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;
然后这会有效,因为你正在改变你自己的受保护成员 class(通过继承存在于该类中)。但是,在您的情况下,您尝试在其他包中更改不同类的受保护成员。因此,您被拒绝访问也就不足为奇了。
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.
这篇关于java - 使用基类实例在派生类中访问的受保护成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!