2012-01-31 55 views
0

A和AService是基類。更好的方法來做這個代碼

B和BService擴展了這些類。

A和B是包含服務參數的bean。

BService需要執行方法中的B類型參數。

public class A 
{ 
    private int a1; 

    public int getA1() { return a1; } 
    public void setA1(int a1) { this.a1 = a1; } 
} 

public class B extends A 
{ 
    private int b1; 

    public int getB1() { return b1; } 
    public void setB1(int b1) { this.b1 = b1; } 
} 

public abstract class AService 
{ 
    public int execute(A a) 
    { 
     return a.getA1() + getValue(); 
    } 

    public abstract int getValue(A a); 
} 

public class BService extends AService 
{ 
    public int getValue(A a) 
    { 
     B b = (A) a; 

     return b.getB1(); 
    } 
} 

有沒有更好的方法來做這個代碼? 特別是,有沒有辦法避免投射物體?

+1

你在哪裏投出物體?你的問題是什麼?你嘗試了什麼?結果是什麼? – 2012-01-31 11:29:50

+1

抽象方法沒有指定主體 – 2012-01-31 11:29:54

+0

@Balaswamy vaddeman:錯誤的複製/粘貼,編輯。 – 2012-01-31 12:18:22

回答

1

聽起來像generics是你在找什麼。通常,只要你有一個總是可以安全地賦值的具體類,你通常可以通過泛型參數來表達它(並且在編譯時檢查它)。

在這個特殊的例子,你會用它必須是一些子類A的然後你使用它的參數,使一些方法具體到特定類型的泛型參數聲明AService - 在這種情況下getValue方法作爲像

public class AService<T extends A> { 

    // Now this takes a T - i.e. the type that a subclass is parameterised on 
    public abstract int getValue(T a) 

    // Execute will have to take a T as well to pass into getValue - an A 
    // wouldn't work as it might not be the right type 
    public int execute(T a) 
    { 
     return a.getA1() + getValue(a); 
    } 
} 

其中T是一種類型的參數(通常單個大寫字母)。那麼你可以聲明BService爲

public class BService extends AService<B> { 

    // The type is checked by the compiler; anyone trying to pass an instance 
    // of A into this class would get a compile-time exception (not a class cast 
    // at runtime) 
    public int getValue(B b) { 
     return b.getB1(); 
    } 
} 
+0

正是我想要的,謝謝。 – 2012-01-31 12:21:12

相關問題