创建数组时,我创建的最后一个对象将替换之前的前两个对象。
public class Main
{
public static final int NUM_CARS = 3;
private static Scanner scanner;
public static void main(String[] args)
{
Car[] cars;
cars = new Car[NUM_CARS];
cars[0] = new Car( "Toyota Camry", 3400 );
cars[1] = new Car( "Ford F-150", 5000 );
cars[2] = new Car( "Honda Civic", 3000 );
System.out.println( cars[0] );
System.out.println( cars[1] );
System.out.println( cars[2] );
应该使用MPG打印每辆汽车的品牌和型号。但这最终将第三个对象(Civic)打印了三次。这是构造函数:
public class Car
{
private static String model; // Car make and model (e.g. "BMW 328i)
private static double mpg; // Car's miles per gallon
private static double milesDriven; // The total miles driven (odometer)
private static double fuelGallons; // The amount of fuel in the tank (in gallons)
public Car( String carModel, int weight )
{
model = carModel;
if ( weight > 4000 )
mpg = 20.0;
else
mpg = 30.0;
milesDriven = 7;
fuelGallons = 15;
}
我以为“ new”不会覆盖数组中的每个元素,但事实并非如此。
提示:忘记static关键字,这很不好