有人告诉我,Java子类可以继承其超类的所有成员。那么这是否意味着甚至可以继承私有成员?我知道它可以继承受保护的成员。
有人能向我解释一下吗?我现在完全困惑了。
有人告诉我,Java子类可以继承其超类的所有成员。那么这是否意味着甚至可以继承私有成员?我知道它可以继承受保护的成员。
有人能向我解释一下吗?我现在完全困惑了。
Parent
和Child
,其中Child
扩展了Parent
。此外,Parent
有一个名为value
的私有整数。Child
是否继承了私有的value
? 在Java中,继承是被定义为“否”的。但是,在一般的面向对象编程语言中,存在轻微的歧义。Child
无处明确引用value
。也就是说,在Child
中不能使用任何像this.value
的代码,也不能从某些调用代码(显然)使用obj.value
。value
被继承了。如果你认为每个Child
的实例也是Parent
的实例,则该对象必须包含在Parent
中定义的value
。即使Child
类不知道它,每个Child
实例中仍然存在名为value
的私有成员。因此,在这种情况下,你可以说Child
中继承了value
。Java文档
中:JLS
中:您将会100%满意。我在我的电脑上测试过了,我将我的结论发布在这里。只需查看下面编写的程序、查看程序输出并阅读最后给出的结论即可。
如果您想要自己测试,请复制整个程序并将其保存到名为"InheritanceTest.java"的文件中,然后编译并运行它。
// Testing if a subclass can access the private members of a superclass
class Class1 {
private String name;
public void setName(String name) {
this.name = name;
System.out.println("The name has been set successfully.");
}
public void showName() {
System.out.println("The name is: " + name);
}
}
class Class2 extends Class1 {
private int age;
public void setAge(int age) {
this.age = age;
System.out.println("The age has been set successfully.");
}
public void showAge() {
System.out.println("The age is: " + age);
}
public void displayName() {
//Accessing the private member of superclass here
//System.out.println("The name is: " + name); //error, can't compile because access to the private member name of the superclass Class1 is not permitted here.
}
}
class InheritanceTest {
public static void main(String[] args) {
Class1 c1 = new Class1();
Class2 c2 = new Class2();
c1.setName("Name_C1");
c2.setName("Name_C2"); //No error, setName() is a public member of the superclass which indirectly gives access to the private member "name".
c1.showName();
c2.showName(); //No error, showName() is a public member of the superclass which indirectly gives access to the private member "name".
c2.setAge(25);
c2.showAge();
//c2.displayName(); //error
}
}
The name has been set successfully.
The name has been set successfully.
The name is: Name_C1
The name is: Name_C2
The age has been set successfully.
The age is: 25
是的,子类可以间接访问超类的私有成员。但是子类不能直接访问超类的私有成员。
所有公共、私有和受保护的成员(即所有字段和方法)都会被子类继承,但是子类只能直接访问超类的公共和受保护成员。如果从超类继承的成员可以访问超类的私有成员,则子类可以使用该继承的成员来访问超类的私有成员。