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

前端 未结 7 1432
天命终不由人
天命终不由人 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:49

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

    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.

    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");
        }
    }
    

提交回复
热议问题