简体   繁体   English

Java初始化类而不重复自己

[英]Java initializing classes without repeating myself

Is it possible to rewrite the following a bit more concise that I don't have to repeat myself with writing this.x = x; 有没有可能重写以下更简洁,我不必重复自己编写this.x = x; two times? 两次?

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;
    }
}

BoltClock's answer is the normal way. BoltClock的答案是正常的方式。 But some people (myself) prefer the reverse "constructor chaining" way: concentrate the code in the most specific constructor (the same applies to normal methods) and make the other call that one, with default argument values: 但是有些人(我自己)更喜欢反向的“构造函数链接”方式:将代码集中在最具体的构造函数中(同样适用于普通方法)并使另一个调用那个,使用默认参数值:

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;
    }
}

Call the other constructor within this overloaded constructor using the this keyword: 使用this关键字调用此重载构造函数中的其他构造函数:

public cls(int x, int y, int z){
    this(x, y);
    this.z = z;
}

您可以使用启动块来实现此目的。

Very simple: Just write an initialize function like this: 很简单:只需编写一个这样的初始化函数:

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;  
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM