重载方法调用问题 [英] Overloading method invoke issue
问题描述
请让我知道,因为重载是编译时多态性,它会考虑调用该方法的引用变量.假设我们是否有参数重载方法,那么将调用哪个重载方法将由我们调用的方法的参数或对象抛出决定.
请在下面找到我的代码:
package com.overload;类鸟{公共无效电话(鸟鸟){System.out.println("鸟");}}类乌鸦扩展鸟{无效呼叫(乌鸦鸟){System.out.println("乌鸦");}}公共类 OverloadApp {公共静态无效主(字符串 [] args){鸟鸟=新鸟();鸟crowBird = new Crow();乌鸦乌鸦 = 新乌鸦();鸟叫(鸟);//1 - O/P:鸟鸟叫(乌鸦);//2 - O/P:鸟Bird.call(crowBird);//3 - O/P:鸟乌鸦叫(鸟);//4 - O/P:鸟乌鸦叫(乌鸦);//5 - O/P:乌鸦乌鸦电话(乌鸦鸟);//6 - O/P:鸟crowBird.call(鸟);//7 - O/P:鸟crowBird.call(乌鸦);//8 - O/P:鸟crowBird.call(crowBird);//9 - O/P:鸟}}
对于 bird.call(crow);//2 - O/P:Bird
- Bird 将决定调用哪个重载方法或参数 crow 决定调用哪个重载方法.
在看到 O/P 后,我有点困惑.
谢谢,卡马尔
此调用
<块引用>bird.call(crow);//2 - O/P:鸟crowBird.call(乌鸦);//8 - O/P:鸟
call call(Bird Bird)
因为两个变量的声明类型都是Bird
,它只知道Bird
> 方法的版本.它不知道另一个.
但是变量crow
被声明为一个Crow
,所以有两种方法可供选择...
如果是这样,那么为什么crow.call(bird);//4 - O/P:Bird
和crow.call(crowBird);//6 - O/P:Bird
是鸟.在这两种情况下,O/P 应该是Crow",因为声明的类型是 Crow
.– 卡马尔·维尔马
没有.因为变量 bird
和 crowBird
被声明为 Bird
类型,所以它们不能传递给 Crow 版本的方法,虽然它可用于变量 crow
.
Please let me know as Overloading is Compile Time Polymorphism and it consider reference variable for invoking the method. suppose if we have parameter overloaded method than which overloaded method will call will be decided by parameter or object throw which we are invoking method.
Please find below my code:
package com.overload;
class Bird {
public void call(Bird bird) {
System.out.println("Bird");
}
}
class Crow extends Bird {
void call(Crow bird) {
System.out.println("Crow" );
}
}
public class OverloadApp {
public static void main(String[] args) {
Bird bird = new Bird();
Bird crowBird = new Crow();
Crow crow = new Crow();
bird.call(bird); // 1 - O/P:Bird
bird.call(crow); // 2 - O/P:Bird
bird.call(crowBird);// 3 - O/P: Bird
crow.call(bird); // 4 - O/P:Bird
crow.call(crow); // 5 - O/P:Crow
crow.call(crowBird); // 6 - O/P:Bird
crowBird.call(bird); // 7 - O/P:Bird
crowBird.call(crow); // 8 - O/P:Bird
crowBird.call(crowBird); // 9 - O/P:Bird
}
}
For bird.call(crow); // 2 - O/P:Bird
- bird will decide which overloaded method is called or parameter crow decides which overloaded method is called.
As after seeing the O/P I am bit confused.
Thanks, Kamal
This invocations
bird.call(crow); // 2 - O/P:Bird crowBird.call(crow); // 8 - O/P:Bird
call call(Bird bird)
because the declared type of both variables is Bird
which only knows the Bird
version of the method. It does not know the other one.
But variable crow
is declared to be a Crow
so that there are two methods to choose from...
If this is the case than why
crow.call(bird); // 4 - O/P:Bird
and
crow.call(crowBird); // 6 - O/P:Bird
are Bird. In these 2 scenarios O/P should be "Crow" as declared type isCrow
. – Kamal Verma
No.
Because variable bird
and crowBird
are declared to be of type Bird
they cannot be passed to the Crow version of the method, although it is available for variable crow
.
这篇关于重载方法调用问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!