CommencerCommencer gratuitement

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.

The Car class from earlier exercises has been preloaded for you.

Cet exercice fait partie du cours

Introduction to Object-Oriented Programming in Java

Afficher le cours

Instructions

  • Complete the inheritance of the Toyota class from the Car class using the extends keyword.
  • Call the constructor of the Car class from within the Toyota constructor using the super method.
  • Pass the correct matching parameters to the super method from the parameters of the Toyota constructor.
  • Create an instance of Toyota called myToyota with the colorbeing "black", the model being "yaris", and the year being 2014 .

Exercice interactif pratique

Essayez cet exercice en complétant cet exemple de code.

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
       ____ myToyota = new Toyota("____", "____", ____);
       System.out.println(myToyota.model);
    }
}
Modifier et exécuter le code