Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the new keyword do here? [duplicate]

Tags:

java

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.

like image 786
With A SpiRIT Avatar asked Nov 23 '15 14:11

With A SpiRIT


People also ask

What does the new keyword do?

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.

What does the new keyword do in C++?

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.

What is the role of new keyword in Java?

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.


2 Answers

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.

like image 39
Bathsheba Avatar answered Sep 19 '22 09:09

Bathsheba


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.

like image 76
cadrian Avatar answered Sep 22 '22 09:09

cadrian