私有字段是否由子类继承? [英] Are private fields inherited by the subclass?

查看:126
本文介绍了私有字段是否由子类继承?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经读过子类不能继承私有字段或方法。但是,在此示例中

I have read that a subclass cannot inherit private fields or methods. However, in this example

class SuperClass {
    private int n=3;
    int getN() {
        return n;
    }
}

class SubClass extends SuperClass {
    public static void main(String[] args) {
        SubClass e = new SubClass();
        System.out.println("n= " + e.getN());
    }
}

当我运行 main 我得到的输出为 n = 3 。似乎 SubClass SuperClass n >。

When I run main I get the output as n=3. Which seems that SubClass is inheriting the private attribute n from SuperClass.

所以,请解释这里发生了什么。谢谢。

So, please explain what's going on here. Thank you.

推荐答案

子类'有'其超类的字段,但无法直接访问它们。类似地,子类'拥有'私有方法,但你不能直接从子类调用或覆盖它们。

The subclass 'has' the fields of its superclass, but does not have access to them directly. Similarly, the subclass 'has' the private methods, but you cannot call or override them from the subclass directly.

关于继承的Java文档,它说


子类继承其父类的私有成员。

A subclass does not inherit the private members of its parent class.

但是,我觉得将它想象为更有用

However, I find it more useful to think of it as


子类继承其父类的私有成员但无权访问他们

A subclass inherits the private members of its parent class but does not have access to them

但这归结为sematics。

but this boils down to sematics.

这篇关于私有字段是否由子类继承?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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