1

if the 'constructor' allocates memory and initializes instance variables while we create objects then why should we say Object o = new Object();? Why not just Object o = Object();

What actually the new operator does?

limonik
  • 499
  • 1
  • 6
  • 28
Sampad Saha
  • 59
  • 2
  • 5
  • 8
    In short, `new` allocates memory, constructor sets it up. – Pshemo Jan 10 '17 at 13:12
  • 5
    `x = Foo()` is a method call. `x = new Foo()` is a constructor call. `new` does actually affect how the code is understood. – khelwood Jan 10 '17 at 13:12
  • http://stackoverflow.com/q/7019754/982149 – Fildor Jan 10 '17 at 13:12
  • 1
    "The new operator instantiates a class by allocating memory for a new object and returning a reference to that memory. The new operator also invokes the object constructor." from https://docs.oracle.com/javase/tutorial/java/javaOO/objectcreation.html – Fildor Jan 10 '17 at 13:13

2 Answers2

6

Constructors only initialise pre-existing objects. The way to tell the difference between a constructor and a method call is the new keyword. e.g. you can have a method called Object in the class Object but this might not create anything. When you have sub-classes this is even more confusing.

class A {
    A() { } // constructor
    static A A() { return new A(); } // method
    static A B() { return new A(); } // method
}

class B extends A {
    B() { }
}

A b = new B(); // creates a B
A a = B.B(); // creates an A

The point of the new keyword is to make it clear when a new object is created.

BTW You can have a factory method which returns a new object as you suggest, however making it explicit may be considered clearer as to what it is actually doing.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
-2

This works like it does to avoid name collisions.

Let' say you have a class A with the methods C, D, and E, but you also have another class named D, which you want to create an instance of in A.

If there wasn't anything like new, then the compiler would have zero idea if you want to call the method or create a new object.

Bálint
  • 4,009
  • 2
  • 16
  • 27