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

标签 java class object instance-variables protected

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

根据我的理解,我明白

  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/

相关文章:

c++ - 如何使用继承在作为类成员的结构中添加新条目

class - 项目管理器包的 Atom 编辑器图标类是什么?

javascript - 访问奇怪的对象

javascript - 循环对象列表未正确显示

java - Dagger 开关模块

java - 如何 append 到整数

javascript - Js,将静态函数从Class设置为变量对象时 'this'是什么

java - 如何在 hibernate 条件上添加 "on"子句?

java - 所有接口(interface)的父类(super class)

objective-c - 在 Objective-C 的对象数组中访问对象及其属性