Method overriding
📖 Scenario: Imagine you have a basic Vehicle class that can describe a vehicle's sound. You want to create a more specific Car class that changes the sound to something unique for cars.
🎯 Goal: You will create a Vehicle class with a makeSound method. Then, you will create a Car class that overrides the makeSound method to show a different sound. Finally, you will print the sounds from both classes.
📋 What You'll Learn
Create a class called
Vehicle with a method makeSound that returns the string 'Generic vehicle sound'.Create a class called
Car that extends Vehicle.Override the
makeSound method in Car to return the string 'Vroom!'.Create instances of both
Vehicle and Car.Print the result of calling
makeSound on both instances.💡 Why This Matters
🌍 Real World
Method overriding is used when you want a child class to change or extend the behavior of a parent class. For example, different types of vehicles make different sounds, so overriding lets each type show its own sound.
💼 Career
Understanding method overriding is important for writing clean, reusable code in object-oriented programming. It is a common skill needed in software development jobs involving JavaScript or other object-oriented languages.
Progress0 / 4 steps