Java类继承,私有字段可以在子类中访问,为什么? [英] Java class inheritance, private fields accessible in subclass, why?

查看:132
本文介绍了Java类继承,私有字段可以在子类中访问,为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码非常类似于以下内容。

I have code very much like the following.

package my.pkg;

public abstract class X {
    private CapableField field;

    public abstract void doSomething();

    public X(CapableField fieldValue) {
        this.field = fieldValue;
    }
}

并且:

package my.pkg.sub;

public class Y extends my.pkg.X {
    public void doSomething() {
        this.field.doSomething();
    }
}

为什么这是Java中的合法代码?我认为私有意味着该字段不能在子类中直接访问,并且这是类继承的一个相当基本的原则。使 X 具体而不是抽象不会改变任何内容。

Why is this even legal code in Java? I thought "private" meant that the field will not be directly accessible in subclasses, and that this was a fairly basic tenet of class inheritance. Making X concrete instead of abstract changes nothing.

如果我特别需要字段或成员,该怎么办?函数,只能在定义它的类中访问,而不能在定义类的某个随机子类中访问?

What do I do if I specifically want a field, or member function, to be accessible only inside the class where it is defined, and not in some random subclass of the defining class?

推荐答案

这是不可能的。当你解释你的时候可能会错过一些东西问题。

This is impossible. May be you missed something when you explain your question.

这篇关于Java类继承,私有字段可以在子类中访问,为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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