Kick Buttowski
Kick Buttowski

Reputation: 6739

Is anonymous object instantiation possible in Java?

Can anyone tell me the difference between two the lines of code below ?

ArrayList<Car> dat;
dat = (new DataSource()).getCar();

DataSource ds = new DataSource();
dat = ds.getCar(); 

What does it mean to put new DataSource() in parentheses?

At the end, what is the result of dat in these two cases?

 ArrayList<Car> dat;

 ArrayList<Car> dat = new ArrayList();

Note: The getCar helper function returns an ArrayList to dat.

Upvotes: 1

Views: 353

Answers (3)

Dawood ibn Kareem
Dawood ibn Kareem

Reputation: 79838

In

ArrayList<Car> dat;
dat = (new DataSource()).getCar();

the parentheses are superfluous. You can equally write

dat = new DataSource().getCar();

In the other version that you cited, you're doing one extra thing - making a variable that refers to your DataSource, for possible later use.

In answer to your second question,

ArrayList<Car> dat;

does not create an object. There's no ArrayList here, just a variable that doesn't reference anything. On the other hand,

ArrayList<Car> dat = new ArrayList();

creates BOTH an ArrayList AND a variable referencing it.

Upvotes: 4

Ameen
Ameen

Reputation: 2586

There is no practical difference between the two versions of the code you posted. dat will be the same value in both cases.

The second version of the code you posted is more readable to humans, so in terms of code maintenance and readability, you may want to use that version.

Also, in the first version, you won't be able to use the value of (new DataSource()) anywhere else since you are not storing a reference to the result of (new DataSource()). This of course is not an issue if you don't need the result anywhere else in your code.

As for the second part of your question, in java, you can think of ArrayList<Car> dat; to be the same as ArrayList<Car> dat = null;. When you declare a reference like that, it does not point to anything. When you declare it as ArrayList<Car> dat = new ArrayList<Car>; however, you are creating a new ArrayList object and making dat refer to it.

Upvotes: 4

UFL1138
UFL1138

Reputation: 642

The only difference is that in the second example you retain a reference to the DataSource object for the duration of the method call. Also the outer parentheses are extraneous.

Upvotes: 2

Related Questions