Search code examples
c#javainitialization

Can C# style object initialization be used in Java?


In C# it's possible to write:

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

I can see that array initialization can be done in a similar way but can something similar to the above be done in Java too, and if so, what's the syntax?


Solution

  • That initialization syntax is not present in Java.

    A similar approach is to use double brace initialization, where you create an anonymous inner sub class with an initializer block:

    MyClass obj = new MyClass() {{
      // in Java these would be more like this: setFieldX(value);
      field1 = "hello";
      field2 = "world";
      field3 = new MyOtherClass() ...
    }};
    

    Be aware though, that you're actually creating a subclass.

    Another approach is to create a builder for MyClass, and have code like this:

    MyClass obj = new MyClassBuilder().
      withField1("hello").
      withField2("world").
      withField3(new MyOtherClass()).
      build();