I have a final for my java class soon and I was hoping I could get help with a question. It is regarding sample code below:
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;
}
}
The question is “Identify the common coding mistake in Lot’s park method. How would you correct this coding error?”.I have no idea what the mistake is. My original answer was that it is a copy constructor and use the clone() method to correct it. But I am not even sure if it is a copy constructor. I checked their classes using getClass() and they all seem to be of the correct type. I would appreciate if anyone could help me out with this. Thank you all!
EDIT: added the code.
Here is the relevant piece of code:
The only “problem” I see here is the lack of range checking when you park more than
nrVehiclescars (which is done implicitly by the JVM, but I guess your teacher is not satisfied by that), so: