通常はコンストラクターを使用しますが、その必要はありません。
コンストラクターのバージョンは次のとおりです。
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
}
これは次のように使用されます:
MyData myData = new MyData("foo", 10);
ただし、例のようにフィールドがprotected
またはの場合は、コンストラクターを定義せずpublic
に実行できます。これは、Javaで必要なものに最も近い方法です。
// 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;
}
};
出来上がり!