I am coming from C++ so there is one feature of java that I don't quite understand. I have read that all objects must be created using the keyword new
, with the exception of primitives. Now, if the compiler can recognise a primitive type, and doesn't allow you to create an object calling its constructor without new
, what is the reason to have the keyword new
at all? Could someone provide an example when two lines of code, identical except for the presence of new
, compile and have different meaning/results?
Just to clarify what I mean by redundant, and hopefully make my question clearer. Does new
add anything? Could the language have been expressed without new
for instantiation of objects via a constructor?
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.
Instantiation: The new keyword is a Java operator that creates the object. Initialization: The new operator is followed by a call to a constructor, which initializes the new object.
By using "new" in your production code, you are coupling your class with its collaborators. If someone wants to use some other collaborator, for example some kind of mock collaborator for unit testing, they can't – because the collaborator is created in your business logic.
The new keyword ignores return statement that returns primitive value. If function returns non-primitive value (custom object) then new keyword does not perform above 4 tasks. Thus, new keyword builds an object of a function in JavaScript.
Methods and constructors can have the same name.
public class NewTest { public static void main(final String[] args) { TheClass(); new TheClass(); } static void TheClass() { System.out.println("Method"); } static class TheClass { TheClass() { System.out.println("Constructor"); } } }
Whether this language design choice was a good idea is debatable, but that's the way it works.
Believe it or not, requiring the use of new
for constructors is a namespacing thing. The following compiles just fine:
public class Foo { public Foo() {} public void Foo() {} }
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