Is the `new` keyword in java redundant?

后端 未结 5 1450
闹比i
闹比i 2020-11-29 05:29

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

相关标签:
5条回答
  • 2020-11-29 05:51

    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() {}
    }
    
    0 讨论(0)
  • 2020-11-29 05:59

    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.

    0 讨论(0)
  • 2020-11-29 06:02

    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 讨论(0)
  • 2020-11-29 06:03

    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.

    0 讨论(0)
  • 2020-11-29 06:04

    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.

    0 讨论(0)
提交回复
热议问题