search

Home  >  Q&A  >  body text

java子类和父类属性重复问题

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

伊谢尔伦伊谢尔伦2769 days ago949

reply all(8)I'll reply

  • 巴扎黑

    巴扎黑2017-04-18 09:05:21

    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.

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-04-18 09:05:21

    They are all private!

    reply
    0
  • 巴扎黑

    巴扎黑2017-04-18 09:05:21

    The same member variables will not be overwritten, http://blog.csdn.net/iwaich/article/details/9126661

    reply
    0
  • 黄舟

    黄舟2017-04-18 09:05:21

    Variables are not overridden

    reply
    0
  • PHPz

    PHPz2017-04-18 09:05:21

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

    reply
    0
  • 高洛峰

    高洛峰2017-04-18 09:05:21

    It is recommended to post the setter method body. If the super keyword is used, it would be better to discuss this issue later

    reply
    0
  • ringa_lee

    ringa_lee2017-04-18 09:05:21

    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

    reply
    0
  • 大家讲道理

    大家讲道理2017-04-18 09:05:21

    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.

    reply
    0
  • Cancelreply