Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the `new` keyword in java redundant?

Tags:

java

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?

like image 983
juanchopanza Avatar asked Jun 14 '11 07:06

juanchopanza


People also ask

What does New keyword do 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.

Is new keyword in Java a operator?

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.

What is the problem with new keyword in Java?

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.

What is the return type of new keyword?

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.


2 Answers

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.

like image 84
artbristol Avatar answered Oct 07 '22 16:10

artbristol


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() {} } 
like image 27
stevevls Avatar answered Oct 07 '22 16:10

stevevls