下面这个Java程序为什么用到了构造器和get set方法,只用一个不可以吗

class Apple
{
private String color;
private double weight;
public Apple(){}
public Apple(String color, double weight)
{
this.color=color;
this.weight=weight;

}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}

public String toString()
{
return "一个苹果的颜色是;"+color+",重量是"+weight;

}
}
public class ToStringTest {
public static void main(String[] args)
{
Apple a=new Apple("红色",58);
System.out.println(a);
}
}

什么时候用构造器 什么时候用get set方法 什么时候全部都用

封装代码的时候都是 自动生成的getset方法。程序员为了测试代码的时候赋值方便,就给写个构造器而已。。不用纠结这个东西。。以后你写的多了就体会到了
温馨提示:答案为网友推荐,仅供参考

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网