受保护的成员行为一旦被继承。 [英] Protected member behavior once it was inherited.

查看:226
本文介绍了受保护的成员行为一旦被继承。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对保护标识符有些怀疑。在K.Sierra的Sun认证Java程序员学习指南的第一章中,我发现了以下信息:

I've got some doubts regarding protected identifier. In the first chapter of Sun Certified Java Programmer Study Guide by K.Sierra I found the following information:

一旦子类外包继承受保护的成员,该成员(由子类继承)变为私有子类外的任何代码,但子类的子类除外。

我提供了反映上述陈述的示例代码,我绝对清楚。

I provided sample code which reflects the above statement and it is absolutely clear to me.

// Parent class
package package1;

import package2.Child;
public class Parent {

    protected int i = 5;

}

// Child class
package package2;

import package1.Parent;

public class Child extends Parent {

    // variable 'i' inherited

}


package package2;

public class Neighbour {

    public void protectedTesting(){
        Child child = new Child();
        System.out.println(child.i); // no access
    }
}

我已经开始尝试并制作一个小小的改变 - 将Neighbor移到package1。并且可以访问i变量,这对我来说有点令人惊讶,因为它不符合语句对子类之外的任何代码变得私有

I've started experimenting and made a small change - moved Neighbour to package1. And there is an access to "i" variable which is a little bit surprising for me as it is not in accordance to statement "becomes private to any code outside the subclass"

更改后的邻居类:

package package1;

import package2.Child;

public class Neighbour {

    public void protectedTesting(){
        Child child = new Child();
        System.out.println(child.i); // access!
    }
}

请向我澄清。谢谢。

推荐答案

简而言之, protected 也是包私有的对子类可见。即使是JLS也很模糊(JLS§6.6.2):

In short, protected is package-private as well as visible to subclasses. Even the JLS is vague on this (JLS §6.6.2):


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

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.

它指定在包外部,只有子类可以访问受保护的成员。此暗示您还可以访问包中的变量。这是不好的措辞,但真正的是受保护的成员具有包级别可见性以及子类级别的可见性。

It specifies that outside the package, only subclasses can access protected members. This implies that you can also access the variable within the package. It's poor wording, but true nonetheless that protected members have package-level visibility as well as subclass-level visibility.

另请参阅:

  • This related question
  • The Java Trail for access control

这篇关于受保护的成员行为一旦被继承。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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