initialize object directly in java

Viewed 86159

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!

10 Answers

There are two types of Constructors in java.

  1. Default constructor
  2. Parameterized constructor

You should create a parameterized constructor to create your object.

The following does what you want, but not in the way that you would expect.

So in a class calling MyData, you would use

Public MyData x = new MyData();
@PostConstruct public void init() {
     x.setName("Fering");
     x.setAge(18);
}

So once the object is construsted, these commands are run, which allows you to populate the object before anything else runs.

So with this you do not have to use anonymous subclasses, or create new constructors, you can just take the class and then use its functions, before anything else would.

Related