(Using inheritance and super reference:) Consider the class Car and the subclass
ID: 3734378 • Letter: #
Question
(Using inheritance and super reference:) Consider the class Car and the subclass SportsCar. Car has instance data of currentSpeed, type, year, cost, model, color and methods of accelerate, brake, getGasMileage, getInsuranceRate, and determineSpeed. Create a complete class definition for both the Car and the SportsCar. (Note: a sports car may have a racing stripe, which could be stored as a boolean variable, and a maxSpeed, also the number of gears. So the SportsCar class might add instance data of stripe, maxSpeed, and numberGears....)
Explanation / Answer
Car class code:
public class Car
{
//Car has instance data of currentSpeed, type, year, cost, model, color
double currentSpeed,cost;
String type,model,color;
int year;
//default constructor
Car() {}
//parameterized constructor
Car(double currentSpeed,double cost,String type,String model,String color,int year)
{
this.cost=cost;
this.type=type;
this.model=model;
this.color=color;
this.year=year;
}
//methods
public void accelerate(){}
public void brake(){}
public double getGasMileage()
{
return 0;
}
public double getInsuranceRate()
{
return 0;
}
public double determineSpeed()
{
return currentSpeed;
}
//toString() method
public String toString()
{
return "Car [currentSpeed=" + currentSpeed + ", cost=" + cost + ", type=" + type + ", model=" + model
+ ", color=" + color + ", year=" + year + "]";
}
}
SportsCar class code:
public class SportsCar extends Car
{
boolean racingstripe;
double maxSpeed;
int numberOfGears;
//default constructor
SportsCar() {}
//parameterized constructor
public SportsCar(double currentSpeed,double cost,String type,String model,String color,int year,
boolean racingstripe, double maxSpeed, int numberOfGears)
{
//using super reference
super(currentSpeed,cost,type,model,color,year);
this.racingstripe = racingstripe;
this.maxSpeed = maxSpeed;
this.numberOfGears = numberOfGears;
}
//toString() method
public String toString()
{
return "SportsCar [racingstripe=" + racingstripe + ", maxSpeed=" + maxSpeed + ", numberOfGears=" + numberOfGears
+ "]";
}
//driver method to test Car and Sports car instance
public static void main(String[]ar)
{
//creating object of SportsCar and assigning it to Car
Car car =new SportsCar(75.90,78900.90,"Sports","Double Gear","Black and white",2018,false,185,5);
System.out.println(car.toString());
}
}
Output:
SportsCar [racingstripe=false, maxSpeed=185.0, numberOfGears=5]
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.