Inheriting the car class
With inheritance, we can create relationships between Classes and share code, avoiding needless repetition. You will make the Toyota
class inherit all that we have created from the Car
class, and to complete the inheritance, you must call the base class's constructor.
Este exercício faz parte do curso
Introduction to Object-Oriented Programming in Java
Instruções do exercício
- Complete the inheritance of the
Toyota
class from theCar
class using theextends
keyword. - Call the constructor of the
Car
class from within theToyota
constructor using thesuper
method. - Pass the correct matching parameters to the
super
method from the parameters of theToyota
constructor. - Create an instance of
Toyota
calledmyToyota
with thecolor
being"black"
, themodel
being"yaris"
, and theyear
being2014
.
Exercício interativo prático
Experimente este exercício completando este código de exemplo.
public class Main {
// Enable the "Toyota" class to inherit from "Car"
static class Toyota ___ ___ {
public Toyota(String color, String model, int year){
// Call the "Car" constructor using "super()"
___(___, ___, ___);
}
}
public static void main(String[] args) {
// Create "myToyota" instance of Toyota and print out the "model"
___ ___ = new ___;
System.out.println(myToyota.model);
}
static class Car {
public String color;
public String model;
public int year;
private int vehicleNumber;
public Car(String color, String model, int year) {
this.color = color;
this.model = model;
this.year = year;
this.vehicleNumber = 101189;
}
private void deployAirbags() {
System.out.println("airbags deployed");
}
public void turnEngineOn() {
System.out.println("engine is on");
}
public int calculateMPG(int milesDriven, int gallonsUsed) {
return milesDriven / gallonsUsed;
}
}
}