A and AService are base classes.
B and BService extend these classes.
A and B are beans containing parameters for the services.
BService expects a B typed argument in the execute method.
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();
}
}
Is there a better way to do this code ?
In particular, is there a way to avoid to cast objects ?
It sounds like generics are what you’re looking for. Typically, whenever you have a concrete class which can always safely cast a value, you can usually express this via generic parameters (and have it checked at compile time).
In this particular example, you’d declare the
AServicewith a generic parameter which must be some subclass of A. Then you use that parameter to make some methods specific to the particular type – in this case thegetValuemethod, as something likewhere the
Tis a type parameter (conventionally a single uppercase letter). Then you can declare the BService as