这个Java属性继承的例子有什么问题? [英] What's wrong with this example of Java property inheritance?

查看:83
本文介绍了这个Java属性继承的例子有什么问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public class InheritanceExample {
  static public void main(String[] args){
    Cat c = new Cat();
    System.out.println(c.speak());

    Dog d = new Dog();
    System.out.println(d.speak());
  }
}



Animal.java



Animal.java

public class Animal {
  protected String sound;
  public String speak(){
    return sound;
  }
}



Cat.java



Cat.java

public class Cat extends Animal {
  protected String sound = "meow";
}



Dog.java



Dog.java

public class Dog extends Animal {
  protected String sound = "woof";
}






输出:




Output:

null
null

我的动物不会说话。太伤心了。

My animals cannot speak. So sad.

推荐答案

字段不是多态的。你已经声明了三个完全不同的字段...... Cat Dog shadow 隐藏 Animal 中的那个。

Fields aren't polymorphic. You've declared three entirely distinct fields... the ones in Cat and Dog shadow or hide the one in Animal.

最简单(但不一定是最好的)获取当前代码的方法是从 Cat Dog 声音 c $ c>,并在 Cat 继承的 声音字段的值c>和

The simplest (but not necessarily best) way of getting your current code is to remove sound from Cat and Dog, and set the value of the inherited sound field in the constructor for Cat and Dog.

更好的方法是使 Animal abstract,并给它一个受保护的构造函数,它接受声音... Cat 的构造函数Dog 然后将分别调用 super(meow) super(woof)

A better approach would be to make Animal abstract, and give it a protected constructor which takes the sound... the constructors of Cat and Dog would then call super("meow") and super("woof") respectively:

public abstract class Animal {
    private final String sound;

    protected Animal(String sound) {
        this.sound = sound;
    }

    public String speak(){
        return sound;
    }
}

public class Cat extends Animal {
    public Cat() {
        super("meow");
    }
}

public class Dog extends Animal {
    public Dog() {
        super("woof");
    }
}

这篇关于这个Java属性继承的例子有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆