Java 使用超类引用时方法重载不起作用
错误: 主线程java.lang中出现异常。错误:未解决的编译问题: 类型通信中的方法greetString不适用于参数int 我在Human类中重载了该方法,并且能够在直接使用Human对象时调用它 但在将人类对象指定给通信引用时,重写的方法工作正常 而重载不支持为什么? 有谁能帮助我理解这种行为吗?Java 使用超类引用时方法重载不起作用,java,polymorphism,Java,Polymorphism,错误: 主线程java.lang中出现异常。错误:未解决的编译问题: 类型通信中的方法greetString不适用于参数int 我在Human类中重载了该方法,并且能够在直接使用Human对象时调用它 但在将人类对象指定给通信引用时,重写的方法工作正常 而重载不支持为什么? 有谁能帮助我理解这种行为吗? 提前感谢编译器无法知道将哪个运行时对象分配给引用。 例如,您可以将上述代码重新编写为 class Communication { public void greet() {
提前感谢编译器无法知道将哪个运行时对象分配给引用。 例如,您可以将上述代码重新编写为
class Communication {
public void greet() {
System.out.println("Greetings..");
}
public void greet(String custom) {
System.out.println(custom);
}
}
public class Human extends Communication {
public void greet(int n) { //overloading
for (int i = 1; i <= n; i++)
System.out.println(i + " Hey..");
}
public void greet(String name) { //overriding
System.out.println("Hi " + name);
}
public static void main(String[] args) {
Communication communication = new Communication();
communication.greet();
communication.greet("Hello World");
Communication humanCommunication = new Human();
// humanCommunication.greet(2); is not working why?
humanCommunication.greet("Sagar");
Human human = new Human();
human.greet();
human.greet(2);
}
}
编译器只能确定humanCommunication将是类型Communication,因此只允许类型Communication中可用的方法
如果需要使用Human中可用的方法,则需要告诉编译器引用是Human
有两种方法可以做到
将humanCommunication声明为Human类型
调用方法期间强制转换仅在Human中可用。如果引用humanCommunication的动态类型不是Human,则将抛出CastClassException
人类交流。greet2;->应该有用
最后我得到了答案,因为我的朋友说这就是编译时多态性和运行时多态性之间的区别 1方法重载是编译时多态性。 [参考类型确定基于哪个重载版本 已选择声明的参数类型。在编译时发生 调用的实际方法仍然是虚拟方法 调用,但编译器将 已经知道要调用的方法的签名 运行时,参数匹配将已确定 向下,而不是方法所在的类。] 2方法重写是一种运行时多态性。 [其他文件中的对象类型] 单词,单词的类型 网络上的实际实例 堆决定了 方法被选中。 在运行时发生。]
感谢您的评论:通信对其子类了解多少?通信没有方法greetint,所以humanCommunication应该能够调用它吗?但我正在为它分配HumanObject,该对象具有public void greetint n{对于int i=1;i但是人类交流被宣布为一种交流,它是一只披着羊皮的狼,人类交流是人类行为的一个例子,就像一个交流的例子,所以它不能称为greetint,因为交流没有声明它……但是,你可以使用HumanhumanCommunication.greet2;
boolean creatHuman = true;
Communication humanCommunication;
if(createHuman)
humanCommunication = new Human();
else
humanCommunication = new Communication ();