initialize object directly in java

Normally, you would use a constructor, but you don’t have to!

Here’s the constructor version:

public class MyData {
    private String name;
    private int age;

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

    // getter/setter methods for your fields
}

which is used like this:

MyData myData = new MyData("foo", 10);

However, if your fields are protected or public, as in your example, you can do it without defining a constructor. This is the closest way in java to what you want:

// Adding special code for pedants showing the class without a constuctor
public class MyData {
    public String name;
    public int age;
}

// this is an "anonymous class"
MyData myData = new MyData() {
    {
        // this is an "initializer block", which executes on construction
        name = "foo";
        age = 10;
    }
};

Voila!

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)