Can I call default constructor from parameterized constructor inside public class in java?

后端 未结 6 1348
暗喜
暗喜 2021-02-19 22:44

I want to call default constructor from a parameterized constructor inside a public java class.

Can I achieve it?

6条回答
  •  忘掉有多难
    2021-02-19 23:11

    yes you can

    public YourClass() {
        public YourClass() { super();}
        public YourClass(int x) { this();}
    }
    

    provided you have the same argument constructor. This won't work

    public YourClass() {
        public YourClass(int x, int y) { this(); } // compiler error here
        public YourClass(int x) { super(); }
    }
    

    Note: super() calls the super constructor (in this case, class Object, because MyClass extends Object implicitly and class Object has a no arg constructor) that matches the same number of arguments.

    this() calls the constructor of the current class that matches the same number of arguments.

提交回复
热议问题