How do I call one constructor from another in Java?

前端 未结 21 2487
不知归路
不知归路 2020-11-22 01:06

Is it possible to call a constructor from another (within the same class, not from a subclass)? If yes how? And what could be the best way to call another constructor (if th

21条回答
  •  无人共我
    2020-11-22 01:29

    I prefer this way:

        class User {
            private long id;
            private String username;
            private int imageRes;
    
        public User() {
            init(defaultID,defaultUsername,defaultRes);
        }
        public User(String username) {
            init(defaultID,username, defaultRes());
        }
    
        public User(String username, int imageRes) {
            init(defaultID,username, imageRes);
        }
    
        public User(long id, String username, int imageRes) {
            init(id,username, imageRes);
    
        }
    
        private void init(long id, String username, int imageRes) {
            this.id=id;
            this.username = username;
            this.imageRes = imageRes;
        }
    }
    

提交回复
热议问题