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!
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.
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.
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With