public class Demo9_Car {
//我想创建n多辆车,匿名对象是这样做的,那用循环该怎么做?
public static void main(String[] args) {
method(new Car());
method(new Car());
method(new Car()); //匿名对象可以当作实际参数传递
}
//抽取方法提高代码的复用性
public static void method(Car c) {
c.color = "黑色";
c.num = 4;
c.run();
}
}
class Car {
String color; //颜色
int num; //轮胎数
public void run() { //车运行
System.out.println(color + "..." + num);
}
} |
|