The new
keyword in languages like Java, Javascript, and C# creates a new instance of a class.
This syntax seems to have been inherited from C++, where new
is used specifically to allocate a new instance of a class on the heap, and return a pointer to the new instance. In C++, this is not the only way to construct an object. You can also construct an object on the stack, without using new
– and in fact, this way of constructing objects is much more common in C++.
So, coming from a C++ background, the new
keyword in languages like Java, Javascript, and C# seemed natural and obvious to me. Then I started to learn Python, which doesn't have the new
keyword. In Python, an instance is constructed simply by calling the constructor, like:
f = Foo()
At first, this seemed a bit off to me, until it occurred to me that there's no reason for Python to have new
, because everything is an object so there's no need to disambiguate between various constructor syntaxes.
But then I thought – what's really the point of new
in Java? Why should we say Object o = new Object();
? Why not just Object o = Object();
? In C++ there's definitely a need for new
, since we need to distinguish between allocating on the heap and allocating on the stack, but in Java all objects are constructed on the heap, so why even have the new
keyword? The same question could be asked for Javascript. In C#, which I'm much less familiar with, I think new
may have some purpose in terms of distinguishing between object types and value types, but I'm not sure.
Regardless, it seems to me that many languages which came after C++ simply "inherited" the new
keyword – without really needing it. It's almost like a vestigial keyword. We don't seem to need it for any reason, and yet it's there.
Question: Am I correct about this? Or is there some compelling reason that new
needs to be in C++-inspired memory-managed languages like Java, Javascript and C# but not Python?
Best Answer
Your observations are correct. C++ is a complicated beast, and the
new
keyword was used to distinguish between something that neededdelete
later and something that would be automatically reclaimed. In Java and C#, they dropped thedelete
keyword because the garbage collector would take care of it for you.The problem then is why did they keep the
new
keyword? Without talking to the people who wrote the language it's kind of difficult to answer. My best guesses are listed below:new
keyword creates an object on the heap. So, why change expected behavior?Ruby is somewhere in between Python and Java/C# in it's use of
new
. Basically you instantiate an object like this:It's not a keyword, it's a static method for the class. What that means is that if you want a singleton, you can override the default implementation of
new()
to return the same instance every time. It's not necessarily recommended, but it's possible.