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 th
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 came from C++, why are you surprised? Doesn't C++ have the same new
, for the same purpose? Java tries to follow most of C/C++ syntax, that's most likely the reason.
Commenting on artbristol's answer: It is highly improbable that Java designers laid out namespaces first, then were forced to add new keyword. It is very likely the opposite: new
was there first, then they found that it allows them to have constructor names collide with other names.
The new
must be written in Java to create a new object instance.
public class Foo {
public void test() {
final Foo foo1 = new Foo();
final Foo foo2 = Foo();
}
public Foo Foo() {
System.out.println("hello world");
return this;
}
}
Note, that methods starting with an uppercase character are discouraged in Java to avoid the confusion.
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.
I don't now why the java language designers decided to add the new
statement to the java language, but, I don't want to miss it. Even if it could be redundant if it wasn't allowed to give classes, methods and fields the same name, like others have shown already in their answers:
Because - it greatly improves readability. Everytime I read that new
statement, I realize immediately that a new object is born.