public class TestBikes {
public static void main(String[] args){
Bicycle bike01, bike02, bike03;
bike01 = new Bicycle(20, 10, 1);
bike02 = new MountainBike(20, 10, 5, "Dual");
bike03 = new RoadBike(40, 20, 8, 23);
bike01.printDescription();
bike02.printDescription();
bike03.printDescription();
}
}
可以将第3行(Bicycle bike01,bike02,bike03)及其3个实例重写为
Bicycle bike01 = new Bicycle(20, 10, 1);
Bicycle bike02 = new MountainBike(20, 10, 5, "Dual");
Bicycle bike03 = new RoadBike(40, 20, 8, 23);
答案 0 :(得分:2)
您似乎在询问是否可以将变量初始化为其声明的一部分,例如:
Bicycle bike01 = new Bicycle(20, 10, 1);
而不是
Bicycle bike01;
bike01 = new Bicycle(20, 10, 1);
是的,你可以这样做,而人们通常会这样做。它不会改变最终的程序。
旁注:当您发现自己编写bike01
,bike02
等变量名称时,请考虑使用数组或类似名称。
答案 1 :(得分:0)
是的当然,在第一种情况下,您只需在第一种情况下定义它们然后初始化它们,但在第二种情况下,您可以同时定义和初始化它们