java 子类继承 父类, 但子类中 包含和父类相同 属性 ,给子类赋值之后,父类的相同的属性值还是空的。
类定义如下:
public class Person {
private String name;
private String age;
// ignore getter and setter
}
public class Student extends Person {
private String name;
private String score;
// ignore getter and setter
}
public static void main(String[] args){
Student stu = new Student();
stu.setAge("12");
stu.setName("test");
}
debug看到
父类(Person)的name属性值是null,继承的方法是子类会覆盖掉父类相同的方法,但是这属性为什么没覆盖
The attributes of the parent class are private, and the subclass also overrides the methods of the parent class. When overriding the method, it does not call the methods of the parent class, so the attribute value of the parent class is empty.
They are all private!
The same member variables will not be overwritten, http://blog.csdn.net/iwaich/article/details/9126661
Variables are not overridden
It is recommended to post the setter method body. If the super keyword is used, it would be better to discuss this issue later
You can program a method a() in Student, use super to call the method in the Person class, and then call the a() method in the main method. It should be feasible
This problem has been solved.
I just point out some inaccuracies in the title description:
In fact, according to my understanding: "The effect of subclass attributes on the attributes of the parent class with the same name" and "the effect of the subclass method on the method of the parent class with the same name" are the same.
In fact, the so-called subclass "covers" the method of the same name of the parent class, but it is not actually covered. The parent class method is still there. It's just that you can't see it in the debug basis.