java子类和父类属性重复问题
伊谢尔伦
伊谢尔伦 2017-04-18 09:03:21
0
8
951

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,继承的方法是子类会覆盖掉父类相同的方法,但是这属性为什么没覆盖

伊谢尔伦
伊谢尔伦

小伙看你根骨奇佳,潜力无限,来学PHP伐。

reply all(8)
巴扎黑

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

PHPzhong
变量是局部变量,你定义成public也不是同一个变量啊。这是两个家庭,恰好有一个孩子名字相同,但本质上是两个不同的变量。
小葫芦

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:

The name attribute value of the parent class (Person) is null. The inheritance method is that the subclass will override the same method of the parent class, but why is this attribute not overridden?

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template