Java 多态性和继承问题



首先,我认为Java的多态函数是由它的参数实例类型映射的。

请有人帮助解释为什么我的函数没有调用myFunction(EmployeeImpl emp)签名实例EmployeeImpl

public class MainApp {
  public static void main(String[] args){
    Employee emp = new EmployeeImpl();
    emp.callMyFunction();
  }
}
abstract class Employee{
  public void callMyFunction(){
    //here is huge amount of code, which all child class has the same
    //excepted this line is called to a different function by it instant types.
    EmployeeFacade.myFunction(this);
  }
}
class EmployeeImpl extends Employee{
}
class EmployeeFacade{
  public static void myFunction(Employee emp){
    //same data to database
    System.out.println("Employee: "+ emp.getClass().getName());
  }
  public static void myFunction(EmployeeImpl emp){
    //same data to database
    System.out.println("EmployeeImpl: "+ emp.getClass().getName());
  }
}
结果:员工

:员工

编辑:这只是一个与我的现实应用程序具有相同结构的示例应用程序,它有 20 多个子类,其中包含名为 callMyFunction 的相同函数,此函数有 20 多行代码。 因此,对于所有子类来说,使用相同的代码代码override这个函数是一项非常艰巨的工作。 无论如何, 如果我需要更改未来的功能会怎样?我会使用相同的代码更改所有 20 个函数吗?

还有比这更容易

的吗?

重载方法不存在动态绑定...

Java 对重载方法使用静态绑定,对被覆盖的方法使用动态绑定。

Java 动态绑定和方法覆盖

有 2 种类型的多态性

1(静态多态性

2(动态多态性

您的案例是静态多态性

如果你调试你的代码,它总是被称为

public static void myFunction(Employee emp){
  System.out.println("Employee: "+ emp.getClass().getName());
}

并且每个类都具有getClass((方法,并且返回具有调用方法的对象的运行时类。这是对象类的JDK实现

 public final native Class<?> getClass();

它是类类实现

    public String getName() {
    String name = this.name;
    if (name == null)
        this.name = name = getName0();
    return name;
}

以 String 形式返回由 Class 对象表示的实体(类、接口、数组类、基元类型或 void(的名称。

我的第一个解决方案(正如我在评论中建议的那样(是将myFunctionEmployeeFacade移动到EmployeeEmployeeImpl和其他子类,从而直接使用虚拟方法。如果由于某些原因无法选择,我的下一个解决方案是将虚拟"代理"功能引入Employee并使用它来正确调度呼叫:

public class MainApp {
  public static void main(String[] args){
    Employee emp = new EmployeeImpl();
    emp.callMyFunction();
  }
}
abstract class Employee
{
    public void callMyFunction()
    {
        //here is huge amount of code, which all child class has the same
        //excepted this line is called to a different function by it instant types.
        callMyFunctionImpl();
    }
    protected void callMyFunctionImpl()
    {
        EmployeeFacade.myFunction(this);
    }
}
class EmployeeImpl extends Employee
{
    @Override
    protected void callMyFunctionImpl()
    {
        EmployeeFacade.myFunction(this);
    }
}
class EmployeeFacade
{
    public static void myFunction(Employee emp)
    {
        //same data to database
        System.out.println("Employee: " + emp.getClass().getName());
    }
    public static void myFunction(EmployeeImpl emp)
    {
        //same data to database
        System.out.println("EmployeeImpl: " + emp.getClass().getName());
    }
}

最新更新