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

后端 未结 6 1027
执念已碎
执念已碎 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 15:59

    You can use the @override annotation to inform the compiler that you are trying to override a method within the superclass.

    e.g.

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

    In your code, now the compiler will generate an error, because this method does not override eat, you need to have the same parameter type.

    However, changing the Flesh parameter to Food type will resolve the problem:

    class Dog extends Animal{
    
        @Override
        public void eat(Food food){
            System.out.println("Dog eats "+ food);
        }
    }
    

    Now you can do the following:

    public class MyUtil {
    
        public static void main(String[] args) {
    
            Animal animal = new Dog(); 
    
            Food food = new Flesh();
    
            animal.eat(food);
        }
    }
    

提交回复
热议问题