user2022068
user2022068

Reputation:

Code duplication vs type casting vs?

Lets suppose I have such classes:
ParentA,ChildA1,ChildA2...ChildAn
ParentB,ChildB1,ChildB2...ChildBn

So, every ChildAi class extends ParentA, and every ChildBi class extends ParentB class.

In class ChildAi I need to work with class ChildBi. For example:

public class ChildAi extends ParentA{
   public ChildBi getChildB(...){
   ....some logic....
   return childBi;
  }
}

So the problem is with method getChildB. If I put this method in ParentA, that I can return only ParentB class and I will always have to do casting. If I put this method in ChildAi than I will always duplicate this method and at least some logic of it. How can I solve it? Is it possible to solve such problem without generics?

Upvotes: 0

Views: 83

Answers (1)

AlexR
AlexR

Reputation: 115398

I think that generics is your friend here.

Define class ParentA as folloiwing:

public class ParentA<T extends {
   public abstract T getB();
}

Now each subclass will define the generic type as following:

public class ChildA1 extends ParentA<ChildB1> {
    public ChildB1 getB() { return ...;}
}

That's it. No casting and no duplicate code.

Upvotes: 1

Related Questions