简体   繁体   English

基于编译器解析的Java重载

[英]Java overloading based on compiler resolution

class Animal {}

class Bull extends Animal {}

class Test {

  void m1(Animal a) {
    System.out.println("Calls Animal class");
  }

  void m1(Bull b) {
    System.out.println("Calls Bull class");
  }

  public static void main(String...args)

  {

    Test t = new Test();

    Animal a = new Bull();

    t.m1(a);
  }
}

RESULT: Calls Animal Class结果:调用动物类

In the above code, both methods having arguments types of parent and child reference can accept the argument of the Bull object.在上面的代码中,参数类型为父引用和子引用的方法都可以接受 Bull 对象的参数。 However, only the method containing the parent reference gets executed.但是,只有包含父引用的方法才会被执行。 Why does this happen?为什么会这样?

This happens because you have two different methods with different reference types one Animal and another Bull .发生这种情况是因为您有两种不同的方法,它们具有不同的引用类型,一个是Animal ,另一个是Bull So when you can a method and pass the parameter type of Animal , this method has been called因此,当您可以一个方法并传递Animal的参数类型时,该方法已被调用

void m1(Animal a) {
   System.out.println("Calls Animal class");
}

Your assumption is true about Java polymorphism when you have a reference of Animal points to object of Bull so whatever you use inside in the two objects will use the child in case of overload otherwise will use Parent if the child doesn't contain override methods.当您将Animal点引用到Bull对象时,您对 Java 多态性的假设是正确的,因此无论您在两个对象内部使用什么都将在重载的情况下使用子级,否则如果子级不包含覆盖方法,则将使用 Parent。 The opposite in C# language depends on the reference to execute not the object. C# 语言中的相反依赖于执行的引用而不是对象。

在此处输入图像描述

But in your case you have a different case, you have two different methods and different parameters, so the compiler finds the method that matches the parameter type and calls it.但是在您的情况下,您有不同的情况,您有两种不同的方法和不同的参数,因此编译器会找到与参数类型匹配的方法并调用它。

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM