这是面试问题。

子类继承private吗 字段?

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

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

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

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


当前回答

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

其他回答

私有类成员或构造函数只能在顶层类的主体(§7.6)中访问,该主体包含了成员或构造函数的声明。它不是由子类继承的。https://docs.oracle.com/javase/specs/jls/se7/html/jls-6.html#jls-6.6

例如,

class Person {
    private String name;

    public String getName () {
        return this.name;
    }

    Person(String name) {
        this.name = name;
    }
}
public class Student extends Person {

    Student(String name) {
        super(name);
    }
    
    public String getStudentName() {
        return this.getName(); // works
        // "return this.name;" doesn't work, and the error is "The field Person.name is not visible"

    }
}

public class Main {
    public static void main(String[] args) {
        Student s = new Student("Bill");

        String name = s.getName(); // works
        // "String name = s.name;" doesn't work, and the error is "The field Person.name is not visible"

        System.out.println(name);
    }
}

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


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

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

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

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


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

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

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

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

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

 

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

我必须回答,Java中的私有字段是继承的。请允许我演示一下:

public class Foo {

    private int x; // This is the private field.

    public Foo() {
        x = 0; // Sets int x to 0.
    }

    //The following methods are declared "final" so that they can't be overridden.
    public final void update() { x++; } // Increments x by 1.
    public final int getX() { return x; } // Returns the x value.

}


public class Bar extends Foo {

    public Bar() {

        super(); // Because this extends a class with a constructor, it is required to run before anything else.

        update(); //Runs the inherited update() method twice
        update();
        System.out.println(getX()); // Prints the inherited "x" int.

    }

}

如果你在一个程序中运行Bar Bar = new Bar();,那么你总是会在输出框中看到数字“2”。由于整数“x”被update()和getX()方法封装,因此可以证明该整数是继承的。

令人困惑的是,因为不能直接访问整数“x”,所以人们认为它不是继承的。然而,类中的每一个非静态的东西,无论是字段还是方法,都是继承的。