【问题标题】:Java: Why do the attributes of a child class change into the default values of the parent class by saving a child as a parent? [duplicate]Java:为什么通过将子类保存为父类,子类的属性会变为父类的默认值? [复制]
【发布时间】:2020-01-05 00:37:57
【问题描述】:

我还在学习 Java(这是我关于 SO 的第一个问题),所以如果这类问题放错了地方或者我的措辞不正确,请原谅我!

我目前正在研究继承和多态性,尽管谷歌搜索了很多,但无法回答我的以下问题。

public class Animal {
    public String name = "Bello";

}

public class Cat extends Animal {
    public String name = "Kitty";

    public static void main(String[] args) {

        Cat cat1 = new Cat();
        Animal animal1 = cat1;
        System.out.println(cat1.name);
        System.out.println(animal1.name);
    }
}

System.out.println(cat1.name); 打印出Kitty,但System.out.println(animal1.name); 打印出Bello

所以显然属性 name 的值随着子类的实例被保存为父类的对象而改变。 为什么父类将值更改为她自己的默认值,即使它已经在 cat1 中设置? 好像有什么。要知道我无法弄清楚..

【问题讨论】:

  • 这叫做shadowing;您有两个单独的字段,每个字段都命名为name。您正在根据变量的编译时类型访问不同的字段。
  • 这个概念被称为field -or attribute-hiding。它是 Java 继承模型的一部分。一般来说,隐藏字段被认为是“不好的做法”。

标签: java inheritance polymorphism parent-child


【解决方案1】:

父类和子类中同名的变量称为变量隐藏。但是子类可以访问这两个属性。

使用下面修改后的代码中显示的 this 和 super 关键字访问它

class Animal {
    public String name = "Bello";

}

public class Cat extends Animal {
    public String name = "Kitty";

    Cat(){
        System.out.println(this.name); //Kitty
        System.out.println(super.name); //Bello
    }

    public static void main(String[] args) {

        Cat cat1 = new Cat();
        Animal animal1 = cat1;

        System.out.println(cat1.name);
        System.out.println(animal1.name);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多