Java Inheritance – How to Avoid Code Duplication with Unmodifiable Classes

inheritancejavaobject-oriented-design

I already have this core class structure that can not be changed:

class A {
    //some basic fields and methods
}
class B {
    //some another basic fields and methods
}

It is core classes and I'm adding some functionality in addition to the existing system.
I need to add some common functionality to this classes. It's implementation is almost identical for A and B. My current solution is to build something like this:

class A {
    //some basic fields and methods
}
class B {
    //some another basic fields and methods
}

class Foo extends A {
    //my new features
}
class Bar extends B {
    //my new features (identical with Foo)
}

The problem is that I can't change A or B class and not only I can't change them, I need both base A and B classes and my Foo and Bar classes to exist. So using reflection to change A and B classes is not a solution.

I also tried to add this functionality as some api-object:

class FeatureApi {
    my new features
}
class Foo extends A {
    FeatureApi api;
}
class Bar extends B {
    FeatureApi api;
}

But get another problem: new methods need access to my classes fields/methods. But I don't have them in api-object.

In summary:

  • I can't change existing classes
  • I want to create some custom classes, that extends A and B
  • I don't need access to any private fields.
  • Besides specific changes, my classes will have a lot of identical features for both.

UPD 2
The main purpose is to implement exactly same behaviour in two custom classes, that inherited from two anchangable base classes. As I see now, inheritance of base classes not making any sense, so removed it and clarified my question.

Best Answer

you can do it with your FeatureApi example. you need a couple of modifications to expose the protected fields in A or B to the wrapped FeatureApi

(im going to go with c#)

class FeatureApi 
{
    FeatureApi(IExposeStuff parent) {..}

    public string myNewFeature()
    {
       var info = parent.GetProtectedInfo();
       //do stuff
    }
}

interface IExposeStuff
{
    string GetProtectedInfo();
}

class NewA : A, IExposeStuff
 {
    FeatureApi api;
    public NewA()
    {
        this.api = new FeatureApi(this)
    }

    public string GetProtectedInfo()
    {
        return this.protectedInfo;
    }
}
Related Topic