gpt4 book ai didi

java - 父类可以看到子类的 protected 变量吗?

转载 作者:行者123 更新时间:2023-12-01 19:50:23 27 4
gpt4 key购买 nike

我对继承的工作原理非常模糊,只是想确保我正在寻找正确的方向。

根据我的理解,我明白

  1. 所有包都可以访问公共(public)变量,
  2. 默认在单个包内,
  3. 仅在类内私有(private),
  4. 并用子类进行保护。

我知道子类可以看到父类的 protected 变量。

我的问题:反之亦然吗?

最佳答案

Does it work the other way around?

不,如果它们不在同一个包中,则不会。根据Java access control tutorial中的表格, protected 将成员公开给子类和同一包中的其他类,而不是父类(super class):

                  Access Levels+−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+| Modifier     Class  Package  Subclass  World || public         Y       Y        Y       Y    || protected      Y       Y        Y       N    || no modifier    Y       Y        N       N    || private        Y       N        N       N    |+−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+

来自 the JLS :

6.6.2. Details on protected Access

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.

父类(super class)不负责子类对象的实现。

你可以自己测试一下:

b/Base.java:

package b;

import a.Example;

public class Base {
public static void showAnswer(Example e) {
System.out.println(e.answer); //
}
}

a/Example.java:

package a;

import b.Base;

public class Example extends Base
{
protected int answer = 42;

public static void main(String[] args)
{
Example e = new Example();
Base.showAnswer(e);
}
}

尝试编译失败:

./b/Base.java:7: error: answer has protected access in Example        System.out.println(e.answer); //                             ^1 error

关于java - 父类可以看到子类的 protected 变量吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51494532/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com