为什么子类不继承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要访问超类的私有成员,您需要使用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
热门推荐
10 儿子立冬祝福语简短独特
11 对当兵的祝福语简短
12 侄儿高考试祝福语简短
13 伴郎红包祝福语朋友简短
14 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短