Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
339 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...