直接在Java中初始化对象 [英] initialize object directly in java
本文介绍了直接在Java中初始化对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以像在Java中使用String类那样直接初始化对象?
Is that possible to initialize object directly as we can do with String class in java:
例如:
String str="something...";
我想为我的自定义课程做同样的事情:
I want to do same for my custom class:
class MyData{
public String name;
public int age;
}
有可能像
MyClass obj1={"name",24};
或
MyClass obj1="name",24;
初始化对象? 或怎么可能!
to initialize object? or how it can be possible!
推荐答案
通常,您可以使用构造函数,但不必这样做!
Normally, you would use a constructor, but you don't have to!
这是构造函数版本:
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中最接近您想要的方式:
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!
这篇关于直接在Java中初始化对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文