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方法。程序员为了测试代码的时候赋值方便,就给写个构造器而已。。不用纠结这个东西。。以后你写的多了就体会到了
温馨提示:答案为网友推荐,仅供参考