Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Object declaration and initialisation

When constructing a new object, I use the following code. In this code, is the object reference the variable 'a'?

BankAcc a = new BankAcc();

Also, out of interest, if the above constructs a new object to the variable a, what does the following do? Does it just create a new object without a variable/object reference?

new BankAcc();

Thanks!

like image 963
mino Avatar asked Dec 31 '11 15:12

mino


People also ask

How do you declare and initialize an object in Java?

Creating an Object Declaration − A variable declaration with a variable name with an object type. Instantiation − The 'new' keyword is used to create the object. Initialization − The 'new' keyword is followed by a call to a constructor. This call initializes the new object.

What is declaration and initialization in Java?

Declaration tells the compiler about the existence of an entity in the program and its location. When you declare a variable, you should also initialize it. Initialization is the process of assigning a value to the Variable. Every programming language has its own method of initializing the variable.

What is object initialisation?

The object initializers syntax allows you to create an instance, and after that it assigns the newly created object, with its assigned properties, to the variable in the assignment. Object initializers can set indexers, in addition to assigning fields and properties.


1 Answers

Yes and yes.

The second one might be useful when you just want to use an anonymous object without caring about having a reference. Like:

new Thread(new Runnable() {
     public void run () { }
}).start();
like image 170
Tudor Avatar answered Sep 29 '22 19:09

Tudor