我的 Java 课程很快就要期末考试了,我希望能得到问题的帮助。这是关于下面的示例代码:
package test;
public class Exam2Code
{
public static void main ( String[ ] args )
{
Lot parkingLot = new Lot();
Car chevy = new Car( );
Car camry = new Car( );
MotorCycle harley = new MotorCycle( 3 );
MotorCycle honda = new MotorCycle( );
parkingLot.park ( chevy );
parkingLot.park ( honda );
parkingLot.park ( harley );
parkingLot.park ( camry );
System.out.println( parkingLot.toString( ) );
System.out.println(chevy.getClass());
System.out.println(camry.getClass());
System.out.println(harley.getClass());
System.out.println(honda.getClass());
}
}
package test;
public class Vehicle
{
private int nrWheels;
public Vehicle( )
{ this( 4 ); }
public Vehicle ( int nrWheels )
{ setWheels( nrWheels); }
public String toString ( )
{ return "Vehicle with " + getWheels()
+ " wheels"; }
public int getWheels ( )
{ return nrWheels; }
public void setWheels ( int wheels )
{ nrWheels = wheels; }
}
package test;
public class MotorCycle extends Vehicle
{
public MotorCycle ( )
{ this( 2 ); }
public MotorCycle( int wheels )
{ super( wheels ); }
}
package test;
public class Car extends Vehicle
{
public Car ( )
{ super( 4 ); }
public String toString( )
{
return "Car with " + getWheels( ) + " wheels";
}
}
package test;
public class Lot
{
private final static int MAX_VEHICLES = 20;
private int nrVehicles;
private Vehicle [] vehicles;
public Lot ( )
{
nrVehicles = 0;
vehicles = new Vehicle[MAX_VEHICLES];
}
public int nrParked ( )
{ return nrVehicles; }
public void park ( Vehicle v )
{ vehicles[ nrVehicles++ ] = v; }
public int totalWheels ( )
{
int nrWheels = 0;
for (int v = 0; v < nrVehicles; v++ )
nrWheels += vehicles[ v ].getWheels( );
return nrWheels;
}
public String toString( )
{
String s = "";
for (Vehicle v : vehicles){
if(v != null){
s += v.toString( ) + "\n";
}
}
return s;
}
}
问题是“找出 Lot 的 park 方法中常见的编码错误。你将如何纠正这个编码错误?”。我不知道错误是什么。我最初的答案是它是一个复制构造函数,并使用 clone() 方法来纠正它。但我什至不确定它是否是一个复制构造函数。我使用 getClass() 检查了他们的类,它们似乎都是正确的类型。如果有人能帮助我解决这个问题,我将不胜感激。谢谢你们!
编辑:添加了代码。