在Java中,是否可以通过传递超类方法中使用的参数的子类来覆盖方法? [英] In java, Can we override a method by passing subclass of the parameter used in super class method?
问题描述
按照规则,在覆盖子类中的方法时,无法更改参数,并且必须与超类中的参数相同. 如果我们在覆盖方法时传递参数的子类怎么办? 它会被称为超载还是超载?
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 while overriding method ? Will it be called as overloading or overriding?
根据我的查询,我在下面编写了一些代码.
我原以为狗吃肉食"的输出,但令我惊讶的是动物吃肉食"的输出
如果有人可以解释分配的对象为Dog类型的对象时,动物方法是如何调用的,将不胜感激.
Based on my query I have written some code below.
I was expecting the output as "Dog eats Flesh Food" but to my surprise the output is "Animal eats Flesh Food"
Will appreciate if someone can explain how does Animal method gets called when the object assigned is of type Dog ?
class Food {
public String toString(){
return "Normal Food";
}
}
class Flesh extends Food {
public String toString(){
return "Flesh Food";
}
}
class Animal {
public void eat(Food food){
System.out.println("Animal eats "+ food);
}
}
class Dog extends Animal{
public void eat(Flesh flesh){
System.out.println("Dog eats "+ flesh);
}
}
public class MyUtil {
public static void main(String[] args) {
Animal animal = new Dog();
Flesh flesh = new Flesh();
animal.eat(flesh);
}
}
推荐答案
Dog
中的方法eat
不会覆盖Animal
中的方法eat
.这是因为参数不同(一个要求Flesh
,另一个要求Food
).
The method eat
in Dog
does not override the method eat
in Animal
. This is because the arguments are different (one requires Flesh
, the other requires Food
).
eat
方法是重载.
重载之间的选择发生在编译时,而不是运行时. 不是基于调用该方法的对象的实际类,而是基于编译时类型(如何声明变量).
Choosing between overloads takes place at compile time, not runtime. It is not based on the actual class of the object on which the method is invoked, but the compile-time type (how the variable is declared).
animal
具有编译时类型Animal
.我们知道这是因为变量animal
的声明是Animal animal = ...
.它实际上是Dog
的事实是无关紧要的-必须调用的是Animal
中eat
的版本.
animal
has compile-time type Animal
. We know this because the declaration of the variable animal
was Animal animal = ...
. The fact that it is actually a Dog
is irrelevant - it is the version of eat
in Animal
that must be invoked.
另一方面,Flesh
中的toString
方法确实覆盖了Food
中的toString
方法.
On the other hand, the toString
method in Flesh
does override the toString
method in Food
.
当一个方法替代另一个方法时,该方法所调用的对象的实际类确定运行哪个版本.
When one method overrides another it is the actual class of the object that the method is invoked on that determines which version runs.
在Animal
的eat
方法中,即使该参数具有编译时类型Food
,如果将Flesh
的实例传递给它,它也是Flesh
中的toString
方法将执行.
In the eat
method of Animal
, even though the argument has compile-time type Food
, if you pass an instance of Flesh
to it, it is the toString
method in Flesh
that will execute.
因此您会收到消息"Animal eats Flesh Food"
.
这篇关于在Java中,是否可以通过传递超类方法中使用的参数的子类来覆盖方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!