How do I call one constructor from another in Java?

前端 未结 21 2479
不知归路
不知归路 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;
        }
    }
    
    0 讨论(0)
  • 2020-11-22 01:34

    Within a constructor, you can use the this keyword to invoke another constructor in the same class. Doing so is called an explicit constructor invocation.

    Here's another Rectangle class, with a different implementation from the one in the Objects section.

    public class Rectangle {
        private int x, y;
        private int width, height;
    
        public Rectangle() {
            this(1, 1);
        }
        public Rectangle(int width, int height) {
            this( 0,0,width, height);
        }
        public Rectangle(int x, int y, int width, int height) {
            this.x = x;
            this.y = y;
            this.width = width;
            this.height = height;
        }
    
    }
    

    This class contains a set of constructors. Each constructor initializes some or all of the rectangle's member variables.

    0 讨论(0)
  • 2020-11-22 01:36

    When I need to call another constructor from inside the code (not on the first line), I usually use a helper method like this:

    class MyClass {
       int field;
    
    
       MyClass() {
          init(0);
       } 
       MyClass(int value) {
          if (value<0) {
              init(0);
          } 
          else { 
              init(value);
          }
       }
       void init(int x) {
          field = x;
       }
    }
    

    But most often I try to do it the other way around by calling the more complex constructors from the simpler ones on the first line, to the extent possible. For the above example

    class MyClass {
       int field;
    
       MyClass(int value) {
          if (value<0)
             field = 0;
          else
             field = value;
       }
       MyClass() {
          this(0);
       }
    }
    
    0 讨论(0)
提交回复
热议问题