4

I know I can create an anonymous class when manually creating an instance of it like this:

ClassName c = new ClassName() {
    public void overridenMethod() { method body }
}

Some classes, however, use builder pattern to create a new instance. My question is whether there is a trick that would allow me to create an anonymous class using the builder provided by its superclass.

JohnEye
  • 6,436
  • 4
  • 41
  • 67
  • Maybe I misunderstanding question, but you can return instance of anonymous class as long as that anon class implements/extends type specified as return type of your `ResultType builder.build()`. – Victor Sorokin Oct 26 '12 at 15:18
  • I'm not sure I understand you. Do you suggest I modify the builder? I cannot. I was looking for something similar to my code snippet above. Like `builder.build() {overridenMethod() { method body }}`. I considered builder pattern to be a possible full alternative to standard constructors, but apparently it is not so. – JohnEye Oct 26 '12 at 18:23
  • ah, understood now. In this case dasblinkenlight's answer is the way. – Victor Sorokin Oct 26 '12 at 19:22

2 Answers2

4

No, or at least not directly: in Java you cannot inherit from an instance; you need to inherit from a class.

However, you can build an anonymous class wrapping an instance returned from the builder. You can call methods on the wrapped instance as you see fit, while overriding the ones that you need to override.

final ClassName wrapped = builder.buildClassName();
ClassName c = new ClassName() {
    public void passedThroughMethod1() { wrapped.passedThroughMethod1() }
    public void overridenMethod() { method body }
    public void passedThroughMethod2() { wrapped.passedThroughMethod2() }
};

At this point, c behaves just like the wrapped instance, except for the overridenMethod. An unfortunate consequence is that you cannot access protected members of the wrapped.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

If I understand the question right, you want the builder to return an instance of the anonymous type. If that is the case, I would add a create method in the base class which the builder invokes to create the new instance. In you derived class override create to return an instance of the anonymous class. This assumes that the builder has access to an instance of the base class. Another mechanism is to provide a Supplier to the builder.

Supplier

John B
  • 32,493
  • 6
  • 77
  • 98