Dan Collins
Dan Collins

Reputation: 1018

How do (can?) I write a class that extends a class and a subclass

I have a question that I am not sure has an answer, but its worth a shot because I would like to not have to maintain two copies of code.

I have a library where class B is a subclass of class A. I have written myself a class C, which extends class A. I would like to make it so that B extends C rather than A, however because A and B are 3rd party libraries for which I do not have source, I do not know how to do this.

Currently, the only solution I know is to make a copy of my class C as a class D, and have it extend B, then refer to D rather than B in my code.

I guess in other words, I am trying to extend a superclass, that then propagates to subclasses.

I hope this post is coherent enough.

Thanks!

Upvotes: 0

Views: 112

Answers (2)

Charlie Martin
Charlie Martin

Reputation: 112346

Think about what you'd really like to do: you have classes A, B, and C where

      A
     / \
    B   C

Of these, you wrote C; A and B are third party. You want C to be a sub class of B, which would simply be:

      A
     / 
    B  
   /
  C

That's not conceptually a problem, rewrite C so you have

  class A {}
  class B extends A {}

Those are both third party and unchangeable. Now you have

  class C extends B {}

and that gives what you describe. However, since you're finding it hard, I suspect you may have something like clashing method names. If so, the aggregation is your friend:

 class Cprime {
    A a;
    B b;

and now write new methods for everything you want to include from either A or B.

Upvotes: -1

Don Roby
Don Roby

Reputation: 41127

This sounds like a situation where you might want to consider having your classes delegate to the library classes rather than subclassing them.

Then you should be able to have one class with whatever abilities you're adding, and access the functions of A and B by delegation.

Depending on the details of what you're actually doing, this might be a Decorator Pattern.

With more details on what these classes do, I might be able to give a clearer suggestion...

Upvotes: 2

Related Questions