How to implement constructor wrapping in Java? -


this i'm trying (in java 1.6):

public class foo {   public foo() {     bar b = new bar();     b.setsomedata();     b.dosomethingelse();     this(b);   }   public foo(bar b) {     // ...   } } 

compiler says:

call must first statement in constructor 

is there workaround?

you need implement this:

public class foo {   public foo() {     this(makebar());   }   public foo(bar b) {     // ...   }   private static bar makebar() {     bar b = new bar();     b.setsomedata();     b.dosomethingelse();     return b;   } } 

the makebar method should static, since object corresponding this not available @ point calling method.

by way, approach has advantage does pass initialized bar object foo(bar). (@ronu notes approach not. of course means foo(bar) constructor cannot assume foo argument in final state. can problematical.)

finally, agree static factory method alternative approach.


Comments

Popular posts from this blog

ASP.NET/SQL find the element ID and update database -

jquery - appear modal windows bottom -

c++ - Compiling static TagLib 1.6.3 libraries for Windows -