为什么 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 Person System.out.println("Name: "+super.name); ^ 1 error
要访问父类的私有成员,你需要使用设置器和获取器方法,并使用子类对象调用它们。
示例
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
广告