首先,我认为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());
}
}
Result: Employee: EmployeeImpl
已编辑:这只是一个与我的现实应用程序结构相同的示例应用程序,它有 20 多个子类,它们包含名为 callMyFunction
的相同函数,该函数有 20 多行代码。因此,使用所有子类的相同代码来覆盖
这个函数对我来说是一项非常艰巨的工作。不管怎样,如果我将来需要改变我的功能会发生什么?我可以使用相同的代码更改所有 20 个函数吗?
还有比这更简单的方法吗?
最佳答案
不存在重载方法的动态绑定(bind)...
Java 对重载方法使用静态绑定(bind),对重写方法使用动态绑定(bind)。
关于java多态和继承问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43037864/