Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
309 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 Answer

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...