Can C# style object initialization be used in Java? -



Can C# style object initialization be used in Java? -

in c# it's possible write:

myclass obj = new myclass() { field1 = "hello", field2 = "world", field3 = new myotherclass() { etc.... } }

i can see array initialization can done in similar way can similar above done in java too, , if so, what's syntax?

that initialization syntax is not present in java.

a similar approach utilize double brace initialization, create anonymous inner sub class initializer block:

myclass obj = new myclass() {{ // in java these more this: setfieldx(value); field1 = "hello"; field2 = "world"; field3 = new myotherclass() ... }};

be aware though, you're creating subclass.

another approach create builder myclass, , have code this:

myclass obj = new myclassbuilder(). withfield1("hello"). withfield2("world"). withfield3(new myotherclass()). build();

c# java initialization

Comments

Popular posts from this blog

iphone - Dismissing a UIAlertView -

intellij idea - Update external libraries with intelij and java -

javascript - send data from a new window to previous window in php -