使用超类引用时,方法重载不起作用

时间:2014-10-27 05:14:35

标签: java polymorphism

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);

    }

}

错误: 线程“main”中的异常java.lang.Error:未解决的编译问题: 通信类型中的方法greet(String)不适用于参数(int)。

我在Human类中重载了该方法,并且能够在直接使用Human对象时调用 但是将Human对象分配给Communication时,引用Overridden方法正常工作 和重载不支持为什么? 任何人都能帮我理解这种行为吗? 提前致谢

2 个答案:

答案 0 :(得分:0)

编译器无法知道将哪个运行时对象分配给引用。 例如,您可以将上述代码重写为

boolean creatHuman = true;
Communication humanCommunication;
if(createHuman)
  humanCommunication = new Human();
else 
  humanCommunication = new Communication ();

编译器只能确定humanCommunication属于Communication类型,因此只允许类型为Communication的方法

如果您需要使用Human中可用的方法,则需要告诉编译器Reference是Human 有两种方法可以做到,

  1. 将humanCommunication声明为人类
  2. 在调用仅在Human()中可用的方法时进行转换。如果引用humanCommunication的动态类型不是Human,则抛出CastClassException

    ((Human)humanCommunication).greet(2); - &GT;应该工作

答案 1 :(得分:0)

最后我得到了答案,因为我的朋友说这是编译时多态性与运行时多态性之间的区别
1)方法重载是编译时多态性 [引用类型确定哪个重载版本(基于 选择了声明的参数类型)。发生在编译时 时间。调用的实际方法仍然是虚方法 在运行时发生的调用,但编译器会 已经知道要调用的方法的签名。所以在 运行时,参数匹配已经被固定 下来,而不是该方法所处的阶级。]
2)方法覆盖是运行时多态性 [对象类型(在其他方面) 单词,类型 实际的实例 堆)确定哪个 方法被选中。 在运行时发生。]
感谢您的评论:)