The Car class, as a subclass, acquires the attributes and methods from the Vehicle class, its superclass.
class Vehicle { protected String brand = “Ford”; // Vehicle attribute public void honk() { // Vehicle method System.out .println(“Tuut, tuut!”); }}class Car extends Vehicle { private String modelName = “Mustang”; // Car attribute public static void main(String[] args ) { // Create a myCar object Car myCar = new Car(); // Call the honk() method (from the Vehicle class) on the myCar object myCar .honk(); // Display the value of the brand attribute (from the Vehicle class) and the value of the modelName from the Car class System.out .println(myCar .brand + ” “ + myCar .modelName ); }} |
The “extends” keyword signifies inheritance, indicating that a class derives from another class.
In Java, it’s feasible to inherit attributes and methods from one class to another, with the inheritance concept categorized into two groups.
To achieve inheritance from a class, utilize the “extends” keyword.