java - 使用基类实例在派生类中访问受保护的成员 [英] java - protected members accessed in derived class using base class instance

查看:29
本文介绍了java - 使用基类实例在派生类中访问受保护的成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在派生类中创建了基类的实例并尝试访问受保护的成员.

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

同一个包中的派生类-

package com.core;

public class MyCollection3 extends MyCollection { 

 public void test(){

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

不同包中的派生类 -

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;

然后这会起作用,因为您正在更改您自己的 类(通过继承存在于该类中)的受保护成员.但是,在您的情况下,您正在尝试更改不同包中不同 类的受保护成员.因此,您被拒绝访问也就不足为奇了.

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 - 使用基类实例在派生类中访问受保护的成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆