创建一个Flower类,类中的字段有名称(name)、品种(type)、颜色(color)、销售价格(price),每个字段分别用getName、getType,getColor、getPrice方法返回对应的属性。然后创建三个Flower... 创建一个 Flower类,类中的字段有名称(name)、品种(type)、颜色( color)、销售价格
( price),每个字段分别用 getName、 getType, getColor、 getPrice方法返回对应的属
性。然后创建三个 Flower对象:(玫瑰花、路易十四、深紫色、400)(玫瑰花、朱丽
叶、淡茶色、300)(百合花、地平线、花橙色、450),把这三个对象存储在一个数组对
象中,然后再遍历数组对象读取并打印出来。
package P78T10;
public class Flower {
private String name;
private String type;
private String color;
private String price;
public Flower(String name,String type,String color,String price) {
this.name=name;
this.type=type;
this.color=color;
this.price=price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public void display(){
System.out.println("名字:"+name+",品种:"+type+",颜色:"+color+",价格:"+price);
}//法一用普通的输出方法
public String toString() {
return getClass().getName()+ "[名字:"+name+",品种:"+type+",颜色:"+color+",价格:"+price+"]";
}//法二用重写toString的方法来实现
public static void main(String[] args) {
Flower f[]=new Flower[3];
f[0]=new Flower("玫瑰花","路易十四","深紫色","400");
f[1]=new Flower("玫瑰花","朱丽叶","淡茶色","300");
f[2]=new Flower("百合花","地平线","花橙色","450");
for(int i=0;i<f.length;i++) {
f[i].display();
}
System.out.println();
for(int i=0;i<f.length;i++) {
System.out.println(f[i]);
}
}
}
用toString重写法 进行简洁输出的进一步使用 还能这样实现(tip:这里没有按照题目要求写):
package P78T10;
import java.lang.reflect.Array;
import java.util.Arrays;
public class Flower {
private String name;
private String type;
private String color;
private String price;
public Flower(String name,String type,String color,String price) {
this.name=name;
this.type=type;
this.color=color;
this.price=price;
}
public String toString() {
return getClass().getName()+ "[名字:"+name+",品种:"+type+",颜色:"+color+",价格:"+price+"]";
}//法二用重写toString的方法来实现
public static void main(String[] args) {
Flower f[]=new Flower[3];
f[0]=new Flower("玫瑰花","路易十四","深紫色","400");
f[1]=new Flower("玫瑰花","朱丽叶","淡茶色","300");
f[2]=new Flower("百合花","地平线","花橙色","450");
String a1 = Arrays.toString(f);
System.out.println(a1);
}
}