Constructor and new operator in Java

To create a new object from the Student class in Java, we usually use the following statement

 Student std = new Student(); 

I read that the new statement creates a new object, allocating memory space on the heap, however I also read that the calling Student() constructor creates it. So this is confusion. Which one creates the std object? Is this the new operator or default constructor?

+6
source share
1 answer

This is a legitimate (albeit confusing) method with the same name as the class, new eliminates any ambiguity. new indicates that the JVM should call the instance initialization method for the given list of classes and arguments and return an initialized object (which is referenced by the first (hidden) parameter of the initialization method).

Java designers could probably find an alternative syntax, but they had a design goal that any time memory was allocated on the heap, it must be called explicitly, requiring the new keyword. This probably seems strange, but most of the Java target audience were C and C ++ programmers who were suspicious of garbage collection, this was done so that the developers did not have allocated memory without their knowledge.

+4
source

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


All Articles