Why does java have new? [duplicate]
Possible Duplicate:
Why do C# and Ja开发者_JAVA技巧va bother with the “new” operator?
Why does java have the new keyword? To create an object of type A
, I have to type A a = new A()
.
Java doesn't have stack allocation, so why couldn't that just be simplified to A a = A()
?
Because C++ did it so, I presume. Java was supposed to look superficially like C++, but with a greatly simplified and streamlined language.
In any case, you got a problem there:
class Foo {
private static void A() {
System.out.println("method");
}
public static void main(String[] args) {
A();
}
}
class A {
public A() {
System.out.println("ctor");
}
}
What should happen here? ctor
or method
?
One obvious drawback to your syntax suggestion is found here:
class A {}
class B extends A {
public A A() { return new B() }
public A foo() { return A(); } //ERK
}
What should the above code in the method foo
do? Does it invoke the method named A()
, or the constructor of A
.
Of course you can now have something like what you want using static imports:
public class A {
public static A A() { return new A(); }
}
This can be brought into scope by import static my.stuff.A.*
That you know you are calling a constructor and not a method.
It is arbitrary. Python constructors work more or less like Java constructors, and are just A(), no new required.
In Java, classes, methods, and variables have different namespaces, which means in any scope you could have one of each with the same name. It'd be ambiguous to say A a = A();
, because there could be a method named A()
. Sure, Java could look for a method and use a class constructor if it couldn't find a method...but then, it wouldn't be obvious (from looking just at the code) what it does, and the Java people are big on "purity". Plus, if you happened to add a public A A()
to your class, that line of code takes on a whole different meaning.
It is arbitrary but one could think of many reasons.
One reason would have to do with the mixing of automatic (stack based) and heap-allocation objects and references for them. You know how in C++ you have to be careful about not taking a pointer to an automatic variable? That's one less headache to worry about.
A second reason is likely that Java is generally designed to have low-cost object allocation and low-cost GC for recent objects (thanks to the use of generational garbage collectors). There is therefore no significant benefit to supporting both types of object allocations.
精彩评论