通常,您会使用构造函数,但您不必这样做!
下面是构造函数版本:
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);
但是,如果您的字段是 或 ,如示例中所示,则可以在不定义构造函数的情况下执行此操作。这是Java中最接近你想要的方式:protected
public
// 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;
}
};
瞧!