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?
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?
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.
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.