Are C# style object initializers available in Java

Actually, there is!

Person p = new Person()
{{
    setFirstName("John");
    setLastName("Doe");
    setAddress(new Address()
    {{
        setStreet("1234 St.");
        setCity("Phoenix");
    }});
}};

or even:

Person p = new Person()
{{
    firstName = "John";
    lastName = "Doe";
    address = new Address()
    {{
        street = "1234 St.";
        city = "Phoenix";
    }});
}};

This is called double brace initialization. However I would avoid this idiom as it has some unexpected side-effects, e.g. this syntax actually creates an anonymous inner class Person$1 and Address$.

See also

  • What is Double Brace initialization in Java?
  • Double Brace Initialization

Others have shown the "double brace" initializers, which I think should be avoided - this isn't what inheritance is for, and it will only work as shown when the fields are directly visible to subclasses, which I'd also argue against. It's not really the same thing as C# initializer blocks. It's a hack to take advantage of a language feature designed for other purposes.

If you have more values than you wish to pass to a constructor, you might want to consider using the builder pattern:

Person person = Person.newBuilder()
    .setFirstName("John")
    .setLastName("Doe")
    .setAddress(Address.newBuilder()
        .setStreet("...")
        .setCity("Phoenix")
        .build())
    .build();

This also allows you to make Person immutable. On the other hand, doing this requires the Person class to be designed for this purpose. That's nice for autogenerated classes (it's the pattern that Protocol Buffers follows) but is annoying boiler-plate for manually-written code.


Normally we use constructors in java to such cases

by using a constructor in the class which you want to create an object you can use that to pass the arguments at the object creating step, ex- MyData obj1 = new MyData("name",24);

for this case you have to use parameterized constructor matching to the arguments you pass from the main method

Ex-

MyData(String name, int age){
    this.name=name;
    this.age=age;
    }

The full code as follows

class MyData{
public String name;
public int age;

 MyData(String name, int age){
    this.name=name;
    this.age=age;
    }
     public static void main(String args[]){
        MyData obj1 = new MyData("name",24);

    }
}

Tags:

Java