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

java - How to pass parameters between Request-Scoped Controllers? -

actionscript 3 - Flex: moving a point with rotation doesnt change the point XY? -

ms access - C# - Using OleDbParameter on table name -