2

I want to extend final class in java to add a new method in inherited class. Which pattern should I use?

for example:

final class foo {
}

foo is a final class in java.

I want to extend this in built class to add extra functionality.

class bar extends foo {
    dosomething(){
    }
}

I can't extend final class. what should I do so that bar acts like foo with added functionality?

Is there a pattern to implement this functionality? So that it will execute all the functions of final class with added functionality

beresfordt
  • 5,088
  • 10
  • 35
  • 43
  • The pattern is called aggregation (aka composition) and you can read more about it under [aggregation versus inheritance](http://stackoverflow.com/a/269535/1594449). As @beresfordt pointed out, you have no choice but to aggregate/compose in this circumstance because you are dealing with a final class. And no, there is not an easier way to do it. – gknicker Feb 21 '15 at 01:43

1 Answers1

3

As you can't extend what you can do is to wrap the class and its methods. You won't be able to use the wrapper where the final class is required, but you can implement any interfaces which are on the final class

edit: Also see this discussion Equivalent to extending a final class in Java

final class Foo {
    public String getSomething() {
        //
    }
}

class Bar {
    Foo foo;

    public Bar() {
        foo = new Foo();
    }

    public String getSomething() {
        foo.getSomething();
    }

    public String doSomethingElse() {
        //
    }
}
beresfordt
  • 5,088
  • 10
  • 35
  • 43
  • 1
    I got your point but then I have to write each and every method of foo class in bar class. so that bar class can call same method on foo object. Is there a better way to achieve this? – user2465908 Feb 21 '15 at 01:31
  • 1
    Not really, take the opportunity to improve your regex skills; it's a 30 sec regex or a world of copy/pasting if the final class has a lot of methods – beresfordt Feb 21 '15 at 01:34
  • Thanks for your inputs. I know I can copy paste. I was looking for a pattern to do this where I can avoid copy paste and rewriting – user2465908 Feb 21 '15 at 01:40
  • 1
    @user2465908 - There isn't one. At least not in pure Java. – Stephen C Feb 21 '15 at 01:50
  • 1
    Interface will not work in this case. Because as I mentioned "foo" is a java inbuilt class like String or Integer – user2465908 Feb 21 '15 at 04:28