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

后端 未结 6 1331
暗喜
暗喜 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 22:58

    You can just call default constructor with new operator (like this: new Test();) or this();. just Test() is forbidden because its not a method of class.

    package org.gpowork.test;
    
    public class Test {
        private String field;
        private Long time = 0L; 
        public Test(){
            this.time = System.currentTimeMillis();
            System.out.println("Default constructor. "+this.time);
        }
        public Test(String field){
                this();
            Test instance = new Test();
            this.field = field;
        }
        public static void main(String[] args){
            System.out.println("start...");
            Test t1 = new Test();
            System.out.println("-------");
            Test t2 = new Test("field1");
        }
    }
    

提交回复
热议问题