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

前端 未结 7 1436
天命终不由人
天命终不由人 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 hiding fields. The sound in Animal is not the same String as the sound in Cat.

    One possible solution is to create a constructor and there simply say

    super.sound = "meow";
    

    instead of in the class body saying

    protected String sound = "meow";
    

    to set the field.

提交回复
热议问题