interface - Java: returning subclass in superclass method signature -
i'm working on problem there several implementations of foo
, accompanied several foobuilder
's. while foo
's share several common variables need set, have distinct variables require respective foobuilder
implement specific functionality. succinctness, i'd have foobuilder
's setters use method chaining, like:
public abstract class foobuilder { ... public foobuilder seta(int a) { this.a = a; return this; } ... }
and
public class fooimplbuilder extends foobuilder{ ... public fooimplbuilder setb(int b) { this.b = b; return this; } public fooimplbuilder setc(int c) { this.c = c; return this; } ... }
and on, several different foobuilder
implementations. technically want, however, approach sensitive order of methods calls when method chaining performed. following has method undefined compile errors:
somefoo.seta(a).setb(b)...
requiring developer think order of method calls in chain. avoid this, i'd have setters in foobuilder
somehow return actual implementing subclass. however, i'm not sure how this. best approach?
this question , real problem.
the easiest way deal in java involves use of generics, mentioned in jochen's answer.
there's discussion of issue , reasonable solution in blog entry on using inheritance fluent interfaces, combines generics definition of getthis()
method overriden in builder subclasses solve problem of returning builder of correct class.
Comments
Post a Comment