[英]java polymorphism and inheritance problems
首先,尽管我通过它的参数实例类型来映射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());
}
}
结果:雇员:EmployeeImpl
编辑:这只是一个示例示例应用程序,其结构与我的现实应用程序相同,该应用程序具有20多个子类,这些子类包含名为callMyFunction
的相同函数,此函数具有20多行代码。 因此,对于所有子类而言,使用相同的代码override
此功能对我来说是一项艰巨的工作。 无论如何,如果我将来需要更改功能会怎样? 我会用相同的代码更改所有20个函数吗?
还有比这更容易的吗?
有2种类型的多态性
1)静态多态
2)动态多态性
你的情况是静态多态性
如果您调试代码,它将始终被称为
public static void myFunction(Employee emp){
System.out.println("Employee: "+ emp.getClass().getName());
}
并且每个具有getClass()方法的类都将返回具有被调用方法的对象的运行时类。 这是Object类的JDK实现
public final native Class<?> getClass();
这是Class类的实现
public String getName() {
String name = this.name;
if (name == null)
this.name = name = getName0();
return name;
}
以String形式返回此Class对象表示的实体(类,接口,数组类,原始类型或void)的名称。
我的第一个解决方案(如我在评论中建议的那样)是将myFunction
从EmployeeFacade
移至Employee
, EmployeeImpl
和其他子类,从而直接使用虚拟方法。 如果由于某些原因这不是一个选择,那么我的下一个解决方案是向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());
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.