这是面试问题。

子类继承private吗 字段?

我的回答是“不”,因为我们不能使用“正常的面向对象的方式”访问它们。但是采访者认为它们是继承的,因为我们可以间接或使用反射访问这些字段,并且它们仍然存在于对象中。

回来后,我在javadoc中找到了以下引用:

超类中的私人成员 一个 子类不继承私有 父类的成员。

你知道面试官观点的论据吗?


当前回答

It would seem that a subclass does inherit the private fields in that these very fields are utilized in the inner workings of the subclass (philosophically speaking). A subclass, in its constructor, calls the superclass constructor. The superclass private fields are obviously inherited by the subclass calling the superclass constructor if the superclass constructor has initialized these fields in its constructor. That's just an example. But of course without accessor methods the subclass cannot access the superclass private fields (it's like not being able to pop the back panel of an iPhone to take the battery out to reset the phone... but the battery is still there).

PS 我遇到的关于继承的许多定义之一是: “继承——一种编程技术,允许派生类扩展基类的功能,继承其所有的STATE(重点是我的)和行为。”

私有字段即使不能被子类访问,也是父类的继承状态。

其他回答

不,私有字段不被继承。唯一的原因是子类不能直接访问它们。

不。私有字段没有被继承…所以我们才发明了"保护"这是有意为之。我想这证明了受保护修饰符的存在。


现在来看看上下文。继承是什么意思——如果它存在于从派生类创建的对象中?是的,它是。

如果你的意思是它是否对派生类有用。嗯,没有。

现在,当你进行函数式编程时,父类的私有字段不会以一种有意义的方式继承给子类。对于子类,超类的私有字段与任何其他类的私有字段相同。

在功能上,它不是遗传的。但理想情况是这样的。


好吧,刚刚看了一下Java教程,他们引用了这样的话:

超类中的私人成员 子类不继承父类的私有成员。但是,如果父类具有用于访问其私有字段的公共或受保护方法,则子类也可以使用这些方法。

参见:http://download.oracle.com/javase/tutorial/java/IandI/subclasses.html

我同意,这个领域是存在的。但是,子类在私有字段上没有任何特权。对于子类,私有字段与任何其他类的私有字段相同。

我相信这只是个人观点的问题。你可以左右争论的任何一方。这两种方法都是合理的。

 

填充位/对齐和VTABLE中对象类的包含不被考虑。因此,子类的对象确实为超类的私有成员留有一席之地。但是,它不能从子类的对象中访问…

我将用代码演示这个概念。子类实际上继承了父类的私有变量。唯一的问题是他们不能访问 子对象,除非您为私有变量提供公共getter和setter 在超级班。

考虑包转储中的两个类。子扩展父。

如果我没记错的话,内存中的子对象由两个区域组成。一个是父部分,另一个是子部分。子程序可以访问私有文件 节只能通过父类中的公共方法在其父类的代码中调用。

这样想。波拉特的父亲博尔托克有一个装有10万美元的保险箱。他不想共享他的“私有”变量保险箱。所以,他没有提供保险箱的钥匙。波拉特继承了保险箱。但是,如果他连门都打不开,那又有什么用呢?要是他的 爸爸提供了钥匙。

父母,

package Dump;

public class Parent {

    private String reallyHidden;
    private String notReallyHidden;

    public String getNotReallyHidden() {
        return notReallyHidden;
    }

    public void setNotReallyHidden(String notReallyHidden) {
        this.notReallyHidden = notReallyHidden;
    }

}//Parent

孩子,

package Dump;

public class Child extends Parent {

    private String childOnly;

    public String getChildOnly() {
        return childOnly;
    }

    public void setChildOnly(String childOnly) {
        this.childOnly = childOnly;
    }

    public static void main(String [] args){

        System.out.println("Testing...");
        Child c1 = new Child();
        c1.setChildOnly("childOnly");
        c1.setNotReallyHidden("notReallyHidden");

        //Attempting to access parent's reallyHidden
            c1.reallyHidden;//Does not even compile

    }//main

}//Child

我们可以简单地声明,当父类被继承时,父类的私有成员实际上成为子类的私有成员,并且不能被进一步继承或子类的对象不可访问。