Understanding the Super Keyword in Java
π Scenario: Imagine you are creating a simple program to represent vehicles. You have a basic Vehicle class and a more specific Car class that inherits from Vehicle. You want to use the super keyword to access the parent class's constructor and methods.
π― Goal: You will build two classes: Vehicle and Car. You will use the super keyword to call the parent class constructor and method from the child class. Finally, you will print the details of the car using these calls.
π What You'll Learn
Create a class called
Vehicle with a constructor that takes a String parameter called brand and stores it in an instance variable.Create a method in
Vehicle called displayInfo() that prints the vehicle brand.Create a class called
Car that extends Vehicle and has an additional instance variable model.Use the
super keyword in Car's constructor to call the Vehicle constructor.Override the
displayInfo() method in Car and use super.displayInfo() to print the brand before printing the model.Create an instance of
Car and call its displayInfo() method to show the output.π‘ Why This Matters
π Real World
Using <code>super</code> is common when you want to build new classes based on existing ones, like creating different types of vehicles or employees with shared and unique features.
πΌ Career
Understanding inheritance and the <code>super</code> keyword is essential for Java developers to write clean, reusable, and maintainable code in many software projects.
Progress0 / 4 steps