[英]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.