我很快就有了一個關於我的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;
}
}
問題是「確定地塊的公園方法常見的編碼錯誤,你將如何解決這個編碼錯誤?」我不知道這個錯誤是什麼。我最初的答案是它是一個拷貝構造函數,並使用clone()方法來糾正它。但我甚至不確定它是否是拷貝構造函數。我使用getClass()檢查他們的類,他們似乎都是正確的類型。如果有人能幫我解決這個問題,我將不勝感激。謝謝你們!
編輯:添加了代碼。
在這裏發佈**相關**代碼。 –
它是如何複製構造函數?它既不是構造函數,也不是構造任何東西。這是一種停車方法。 「Lot」公園有多少輛車? –
複製構造函數是一個猜測,因爲該部分討論複製構造函數等。那麼錯誤是不檢查它是否超過了它可以容納的最大車輛數量? – somtingwong