开发者

Is the `new` keyword in java redundant?

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 presenc开发者_如何学Ce 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?


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.


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() {}
}


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜