In java, Can we override a method by passing subclass of the parameter used in super class method?

后端 未结 6 1023
执念已碎
执念已碎 2020-12-11 15:48

As per the rule, while overriding a method in subclass, parameters cannot be changed and have to be the same as in the super class. What if we pass subclass of parameter wh

6条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-11 16:22

    No, we can not in this case you can check it by adding @Override above the eat method in Dog class so compilation error will appear like this :

    @Override
    public void eat(Flesh flesh){
       System.out.println("Dog eats "+ flesh);
    }
    

    Make sure that in override the parameters should be as parent class in type and order.

提交回复
热议问题