0

I have class structure like this:

class A1,A2,..,An extends A;
class B1,B2,..,Bn extends B;

And class that converts Ai into Bi:

    private B1 convert(A1 a1){}
...
    private Bn convert(An an){}

How can I define single public method with signature like <? extends B> convert(<? extends A> a)? Now I have only this approach:

    B convert(A a){
      if(A.getClass().equals(A1.class)){
         return convert((A1)a);
      }...
    }

Can I use instanceof if perfomance is important and the method will be called frequently?

amit
  • 175,853
  • 27
  • 231
  • 333
Borodin.Mik
  • 332
  • 1
  • 4
  • 11
  • 3
    Just a thought: IMHO a more elegant solution will be to declare a method in `A` [preferably abstract, if `A` is abstract]: `public B toB()`, that will create a `B` instance from the caller. – amit Jul 17 '12 at 09:21
  • Is as nice as simply! Thank you! Why I didn't think about it? – Borodin.Mik Jul 17 '12 at 09:36
  • Since it seems to help you, I added it as an answer with a code snap. Glad I could help. – amit Jul 17 '12 at 09:42

2 Answers2

2

A more elegant solution will probably be to declare a method in A: [preferably abstract, if A is abstract]:

public abstract B toB();

Overriding classes (A1,A2,...) will have to override it and instantiate their own B object.

Code snap [the static modifier is used since I implemented it as an inner class, it is not needed and cannot be used if the classes are outer classes]:

public abstract static class A { 
    public abstract B toB();
}
public static class A1 extends A {
    @Override
    public B1 toB() {
        return new B1();
    } 

}

public static class B {

}
public static class B1 extends B { 

}
amit
  • 175,853
  • 27
  • 231
  • 333
0

you could do something like:

public <AType extends A, BType extends B> BType convert(AType a) {...

But your could have converter interface like:

public interface Converter<AType extends A, BType extends B> {

    AType convert(BType b);

    BType convert(AType a);

}

Regarding the performance question, you could take a look here

Community
  • 1
  • 1
Francisco Spaeth
  • 23,493
  • 7
  • 67
  • 106