代码之家  ›  专栏  ›  技术社区  ›  Christian

Java初始化类而不重复我自己

  •  6
  • Christian  · 技术社区  · 15 年前

    有没有可能把下面的内容改写得更简洁一点,这样我就不用在写作中重复了 this.x = x; 两次?

    public class cls{
        public int x = 0;
        public int y = 0;
        public int z = 0;
    
        public cls(int x, int y){
            this.x = x;
            this.y = y;
        }
    
        public cls(int x, int y, int z){
            this.x = x;
            this.y = y;
            this.z = z;
        }
    }
    
    5 回复  |  直到 15 年前
        1
  •  15
  •   leonbloy    15 年前

    博尔特的答案是正常的。但有些人(我自己)更喜欢反向“构造函数链接”方式:将代码集中在最特定的构造函数中(这一点同样适用于普通方法),并使用默认参数值使另一个调用该构造函数:

    public class Cls {
        private int x;
        private int y;
        private int z;
    
        public Cls(int x, int y){
             this(x,y,0);
        }
    
        public Cls(int x, int y, int z){
            this.x = x;
            this.y = y;
            this.z = z;
        }
    }
    
        2
  •  10
  •   BoltClock    15 年前

    使用 this

    public cls(int x, int y, int z){
        this(x, y);
        this.z = z;
    }
    
        4
  •  0
  •   Zacky112    15 年前

    为此,可以使用初始化块。

        5
  •  0
  •   InsertNickHere    15 年前

    public class cls{
        public int x = 0;
        public int y = 0;
        public int z = 0;
    
        public cls(int x, int y){
           init(x,y,0);
        }
    
        public cls(int x, int y, int z){
           init(x,y,z);
        }
    
         public void init(int x, int y, int z ) {
            this.x = x;
            this.y = y;
            this.z = z;  
        }
    }