集册 Java实例教程 编译器如何从重载方法的多个版本中选择最具体的方法

编译器如何从重载方法的多个版本中选择最具体的方法

欢马劈雪     最近更新时间:2020-01-02 10:19:05

477
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
编译器如何从重载方法的多个版本中选择最具体的方法

public class Main {/* from 时代Java - nowjava.com*/

  public double add(int a, int b) {

    System.out.println("Inside add(int a, int b)");

    double s = a + b;    

    return s;

  }

  

  public double add(double a, double b) {

    System.out.println("Inside add(double a, double b)");

    double s = a + b;    

    return s;

  }


  public void test(Employee e) {

    System.out.println("Inside test(Employee e)");

  }


  public void test(Manager e) {

    System.out.println("Inside test(Manager m)");

  }

  /*来自 nowjava.com - 时  代  Java*/

  public static void main(String[] args) {

    Main ot = new Main();


    int i = 10;

    int j = 15;

    double d1 = 1.4;

    double d2 = 2.5;

    float f1 = 1.3F;

    float f2 = 1.5F;

    short s1 = 2;

    short s2 = 6;

    

    ot.add(i, j);

    ot.add(d1, j);

    ot.add(i, s1);

    ot.add(s1, s2);

    ot.add(f1, f2);

    ot.add(f1, s2);

    

    Employee emp = new Employee();

    Manager mgr = new Manager();

    ot.test(emp);

    ot.test(mgr);

    

    emp = mgr;

    ot.test(emp);

  }

}


class Employee {

  private String name = "Unknown";


  public void setName(String name) {

    this.name = name;

  }


  public String getName() {

    return name;

  }


  public boolean equals(Object obj) {

    boolean isEqual = false;


    // We compare objects of the Employee class with the objects of

    // Employee class or its descendants

    
展开阅读全文