Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
313 views
in Technique[技术] by (71.8m points)

initialize object directly in java

Is that possible to initialize object directly as we can do with String class in java:

such as:

String str="something...";

I want to do same for my custom class:

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

is that possible like

MyClass obj1={"name",24};

or

MyClass obj1="name",24;

to initialize object? or how it can be possible!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...