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

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

    You cannot override class fields, only methods. The sound field in your Dog and Cat classes is actually hiding the sound field in the Animal superclass.

    You can, however, access superclass fields from subclasses, so you could do something like this:

    public class Dog extends Animal {
      public Dog() {
        sound = "woof";
      }
    }
    
    public class Cat extends Animal {
      public Cat() {
        sound = "meow";
      }
    }
    

    Or, you can make the Animal class abstract, and declare the speak method abstract too, then define it in subclasses:

    public abstract class Animal {
      public abstract String speak();
    }
    
    public class Dog extends Animal {
      public String speak {
        return "woof";
      }
    }
    
    public class Cat extends Animal {
      public String speak {
        return "meow";
      }
    }
    

提交回复
热议问题