0

I have a 3rd-party library class, which I need to extend with my own implementation. The library class I want to extend is itself a subclass of another library base class.

I want the functionality that the base class provides but not that of the subclass. Is there a way to write my overridden method, such that I can call directly to the (grandparent) base class (LibraryBaseClass) from my subclass?

class LibraryBaseClass
{
    protected void method() // want to call this method
    {
        System.out.println( "LibraryBaseClass" );
        // ... desired functionality here
    }
}

class LibraryClass extends LibraryBaseClass
{
    @Override
    protected void method() // want to skip this method
    {
        System.out.println( "LibraryClass" );
        // ... undesired functionality here
        super.method();
    }
}

class MySubClass extends LibraryClass
{
    @Override
    public void method()
    {
        System.out.println( "MySubClass" );
        super.method(); // would like to call something like LibraryBaseClass.super.method() here
    }
}

// using my method here
new MySubClass().method();

I could just copy and paste the code from LibraryBaseClass.method() into MySubClass.method(), but I'd like to avoid that if possible. I cannot directly edit the library code.

GreenGiant
  • 4,930
  • 1
  • 46
  • 76
  • 2
    Is there other `LibraryClass` behavior that you want to retain? If not, then have `MySubClass` extends `LibraryBaseClass` so you can call `super.method()`. – rgettman Jun 04 '14 at 16:51
  • Yes, I want most of the functionality from `LibraryClass`, just not for this specific method. – GreenGiant Jun 04 '14 at 16:53
  • 1
    Always prefer Composition than Inheritance :) : http://stackoverflow.com/questions/49002/prefer-composition-over-inheritance – lpratlong Jun 04 '14 at 16:54
  • Indeed. Unfortunately in this case, much of the internal functionality desired from the `LibraryBaseClass` and `LibraryClass` are protected methods and hence not accessible when using composition. This, of course, isn't shown in the simple example above. – GreenGiant Jun 04 '14 at 17:16
  • I take that back. I was able to figure out a way to use composition to achieve the functionality I was looking for. I just had to make much more coarse-grained function calls, since I am constrained to the public API. – GreenGiant Jun 04 '14 at 18:27

0 Answers0