gpt4 book ai didi

Java初始化类不再赘述

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:39:42 25 4
gpt4 key购买 nike

是否可以将以下内容重写得更简洁一些,这样我就不必重复编写 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;
}
}

最佳答案

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

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

关于Java初始化类不再赘述,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3299542/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com