13

I know that in Java we can't extend a final class. But is there any alternative way where I get the effect of extending a final class?

Because I have a final class with the requirements I am looking for, so if somehow I can reuse this, it would be of great help for me.

harpun
  • 4,022
  • 1
  • 36
  • 40
GuruKulki
  • 25,776
  • 50
  • 140
  • 201

2 Answers2

28

Create a wrapper for the final class?

Something like this:

class MyClass {
    private FinalClass finalClass;

    public MyClass {
        finalClass = new FinalClass():
    }

    public void delegatingMethod() {
        finalClass.delegatingMethod();
    }
}

A wrapper class like MyClass won't be accepted as an instance of FinalClass. If FinalClass implements any interfaces you can implement them in MyClass to make the classes more alike. The same is true of any non-final parents of the FinalClass; in that case your MyClass design should be compatible with those parent classes though.

It is even possible to create a wrapper class during runtime using reflection. In that case you can use the Proxy class. Beware that proxy classes do require in depth knowledge about the Java type system.

Maarten Bodewes
  • 90,524
  • 13
  • 150
  • 263
Arne Deutsch
  • 14,629
  • 5
  • 53
  • 72
  • 1
    In practice though this only works if the class being wrapped implemented some kind of interface/abstract class and you can provide a wrapper instance in place of the original. If you cannot do either of these then this is difficult to do with out refactoring the original. – Kevin Brock Jan 28 '10 at 08:07
  • Of course you can't replace all instances of FinalClass with MyClass. But you can define your own interface to wrap FinalClass with MyClass. Just never reference FinalClass outside of MyClass. – Arne Deutsch Jan 28 '10 at 09:13
  • @ArneJan, did you mean that I shouldn't refer to the `finalClass` field in any other classes? Why? – Maksim Dmitriev Jul 15 '13 at 14:34
  • The desired effect of GuruKuki was to something like extending a final class. If you then reference the wrapped class outside of the wrapper you deal with two instances of two different classes ... but the goal was to work with ONE instance only. – Arne Deutsch Jul 15 '13 at 17:21
3

The simplest option would be to write a wrapper, which contains an instance of the final class as a member variable and acts as a proxy to the final class.

This way, it's easy to override or extend methods of the final class.

Aaron
  • 6,988
  • 4
  • 31
  • 48