What does the new keyword do here?

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 can not understand the two statements in the main method ( new my_class(); ).

I have never seen this statement other than the definition of an object. I know that a new keyword allocates memory for an object and assigns a reference address, but what happens in this case is completely ambiguous; allocate memory for what?

What does the new keyword do here? Regardless of this, using this operator, I can explicitly call the constructor from the main method. I could not find such a claim anywhere in a textbook or on the Internet.

+5
source share
4 answers

new my_class() creates a new object of type my_class . He is not appointed; therefore it is discarded.

But before being discarded, the object is still built; the constructor starts and prints the value of object a . eight.

+6
source

These two lines create my_class objects and allocate memory in a heap. But you cannot reference these objects later, since you do not store the link anywhere.

+2
source

new my_class(); not only calls the default my_class , but also returns a reference to the newly created object.

Of course, you can refuse this link.

Here is what happens here. Without saving the link, the created object may have the right to garbage collection right away.

+2
source

This actualy code creates 2 my_class , but these objects are not attached to any link, so they will be deleted by GC soon. This seems like an example call.

 int Check() { } 

and it can be called

 object.Check(); 

and it will work.

0
source

Source: https://habr.com/ru/post/1236626/


All Articles