1
假設我有三個類A,B,C。 所有三者都做同樣的事情,但以不同的方式,它們的效率不同。 三個類中的所有方法名稱,變量名都是相同的。將不同類的對象作爲參數傳遞給相同的方法
class A{
public static int method(){
......
return result;
}
}
class B{
public static method(){
......
return result;
}
}
class C{
public static method(){
......
return result;
}
}
我有測試類,它有一個方法來測試上述三個類中的代碼。由於這個testMethod()
對所有三個類都很常見,有沒有辦法用classes A,B,C
的對象調用這個方法?
class Test{
public static int testMethod(Object ABC)
{
return ABC.method();
}
public static void main(String[] args){
A a = new A();
SOP(testMethod(a));
B b = new B();
SOP(testMethod(b));
C c = new C();
SOP(testMethod(c));
}
}
我能想到的唯一方法是爲每個類創建三種不同的方法,就像這樣。
class Test{
public static int testMethodA(A a)
{
return a.method();
}
public static int testMethodB(B b)
{
return b.method();
}
public static int testMethodC(C c)
{
return c.method();
}
public main()
{
//call to each of the three methods
............
}
此場景的最佳方法是什麼?基本上我想只有一種方法可以測試所有三個類。