为什么子类不继承Java中超类的私有实例变量?
当您声明一个类的实例变量为私有时,如果尝试这样做,将无法在另一个类中访问它们,否则将生成编译时错误。
但是,如果您继承具有私有字段的类,包括该类的所有其他成员,则私有变量也将被继承并且可用于子类。
但是,您不能直接访问它们,否则将产生编译时错误。
示例
class Person{private String name;
public Person(String name){
this.name = name;
}
public void displayPerson() {
System.out.println("Data of the Person class: ");
System.out.println("Name: "+this.name);
}
}
public class Student extends Person {
public Student(String name){
super(name);
}
public void displayStudent() {
System.out.println("Data of the Student class: ");
System.out.println("Name: "+super.name);
}
public static void main(String[] args) {
Student std = new Student("Krishna");
}
}
编译时错误
Student.java:17: error: name has private access in PersonSystem.out.println("Name: "+super.name);
^
1 error
要访问超类的私有成员,您需要使用setter和getter方法,并使用子类对象对其进行调用。
示例
class Person{private String name;
public Person(String name){
this.name = name;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public void displayPerson() {
System.out.println("Data of the Person class: ");
System.out.println("Name: "+this.name);
}
}
public class Student extends Person {
public Student(String name){
super(name);
}
public void displayStudent() {
System.out.println("Data of the Student class: ");
}
public static void main(String[] args) {
Student std = new Student("Krishna");
System.out.println(std.getName());
}
}
输出结果
Krishna
以上是 为什么子类不继承Java中超类的私有实例变量? 的全部内容, 来源链接: utcz.com/z/348802.html