且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java:超类对象上子类的受保护访问限制

更新时间:2023-02-18 21:04:16

受保护成员只能通过继承访问同一个包之外 - 即在层次结构中。

Protected members can only be accessed outside of the same package if it's via inheritance - i.e. within the hierarchy.

所以当你从另一个包中创建另一个A实例时,这不是继承关系,因此失败。

So when you're creating another instance of A from a different package, that's not an inheritance relationship and it thus fails.

与往常一样,这在JLS,6.6.2中有所涉及:

As always, this is covered in the JLS, 6.6.2:


对象的受保护成员或构造函数可以从包外部访问,只能通过负责实现该对象的代码来声明它。

A protected member or constructor of an object may be accessed from outside the package in which it is declared only by code that is responsible for the implementation of that object.