Is the `new` keyword in java redundant?

后端 未结 5 1467
闹比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 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.

提交回复
热议问题