class my_class {
int a = 8;
my_class() {
System.out.println(a);
}
}
public class NewClass {
public static void main(String[] argue) {
new my_class();
new my_class();
}
}
I cannot understand the two statements in the main method ( new my_class();
).
I have never seen this statement except in object definition. I know that the new keyword allocates memory for an object and assigns a reference address but what is happening in this case is totally ambiguous; allocate memory for what?
What does the new keyword do here? Whatever this is by using this statement I can explicitly call the constructor from the main method. I could not find such a statement anywhere in a textbook or the internet.
The new keyword in JavaScript: The new keyword is used to create an instance of a user-defined object type and a constructor function. It is used to constructs and returns an object of the constructor function.
new keyword The new operator is an operator which denotes a request for memory allocation on the Heap. If sufficient memory is available, new operator initializes the memory and returns the address of the newly allocated and initialized memory to the pointer variable.
The new keyword in java instantiates a class by allocating it a memory for an associated new object. It then returns a reference for that memory. Many times, the new keyword in java is also used to create the array object.
new my_class();
not only calls the default constructor of my_class
, but it also returns a reference to the newly created object.
You are, of course, free to discard that reference.
That is what is happening here. In not retaining a reference, the created object may well be eligible for garbage collection immediately.
new my_class()
creates a new object of type my_class
. It is not assigned; so it is discarded.
But before being discarded, the object is built anyway; the constructor is run and prints its object's a
attribute value. 8.
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