What's wrong with this example of Java property inheritance?

前端 未结 7 1426
天命终不由人
天命终不由人 2021-01-04 03:39

Inheritance.java

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

            


        
7条回答
  •  失恋的感觉
    2021-01-04 03:52

    You're shadowing the field inherited from Animal. You have a few options, but the prettiest way of doing it is passing the sound in the constructor:

    public class Animal {
      private final String sound;
      protected Animal(String sound){
        if (sound == null)
          throw new NullPointerException("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"); }
    }
    

    This way, you can make sure that an Animal always has a valid sound, right from construction.

提交回复
热议问题