In: Computer Science
Write a program to have a Car class which is comparable. Make the Car class comparable and use speed to compare cars. Write a method in Main class that finds the minimum of 4 things (generically). Create 4 cars and pass the cars to the minimum method and find the smallest car. Have a toString method for the Car class. The main program should be able to find out how many cars are created so far by calling a static method called countCars.
Create another class called LuxCar that extends the class Car. You may have an additional member variable called airCondition of type intger (with setters and getters). Make the variables in Car class protected. Create 4 LuxCar objects and find the smallest one. Does LuxCar objects work with minimum method?
//program to have a Car class which is comparable.
public class Car implements Comparable {
// Make the variables in Car class protected
protected int speed;
protected static int count;
public Car(int s) {
speed = s;
count++;
}
// Make the Car class comparable and use speed to compare
cars
public int compareTo(Object o) {
Car other = (Car) o;
return this.speed - other.speed;
}
// how many cars are created so far by calling a static method
called countCars.
public static int countCars(){
return count;
}
@Override
public String toString() {
return "Car [speed=" + speed +
"]";
}
// a method in Main class that finds the minimum of 4 things
(generically)
public static Car minCar(Car cars[])
{
Car resultCar = cars[0];
int min = resultCar.speed;
for(int
i=1;i<cars.length;i++)
{
if(cars[i].speed<min)
{
resultCar = cars[i];
min = cars[i].speed;
}
}
return resultCar;
}
public static void main(String[] args) {
// Create 4 cars and pass the cars to the
minimum method and find the smallest car.
Car cars[] = new Car[4];
cars[0] = new Car(30);
cars[1] = new Car(20);
cars[2] = new Car(10);
cars[3] = new Car(50);
System.out.println(minCar(cars));
}
}
//class called LuxCar that extends the class Car
class LuxCar extends Car{
// dditional member variable called airCondition of
type intger
int airCondition;
// with setters and getters
public int getAirCondition() {
return airCondition;
}
public void setAirCondition(int airCondition)
{
this.airCondition =
airCondition;
}
public LuxCar(int speed,int airCondition) {
super(speed);
this.airCondition =
airCondition;
}
public static void main(String[] args)
{
// Create 4 LuxCar objects and find
the smallest on
LuxCar luxCars[] = new
LuxCar[4];
luxCars[0] = new
LuxCar(30,10);
luxCars[1] = new
LuxCar(20,20);
luxCars[2] = new
LuxCar(10,30);
luxCars[3] = new
LuxCar(50,40);
System.out.println(minCar(luxCars));
}
}