Java inheritance is a mechanism that allows a class to inherit properties and behaviors from another class. Inheritance is one of the fundamental concepts of object-oriented programming and is used to create hierarchical relationships between classes.
In Java, a class can inherit from one (and only one) superclass using the extends
keyword. The superclass is the class being inherited from, and the subclass is the class that inherits from it.
Here's an example of a simple Vehicle
class and a Car
subclass that inherits from it:
public class Vehicle {
protected String make;
protected String model;
public Vehicle(String make, String model) {
this.make = make;
this.model = model;
}
public void start() {
System.out.println("Starting the vehicle...");
}
public void stop() {
System.out.println("Stopping the vehicle...");
}
}
public class Car extends Vehicle {
private int numDoors;
public Car(String make, String model, int numDoors) {
super(make, model);
this.numDoors = numDoors;
}
public void drive() {
System.out.println("Driving the car...");
}
}
In this example, the Vehicle
class has two instance variables (make
and model
) and two methods (start()
and stop()
). The Car
class extends Vehicle
using the extends
keyword and adds a new instance variable (numDoors
) and a new method (drive()
).
Note that the Car
class calls the super()
method in its constructor to call the Vehicle
constructor and pass in the make
and model
parameters. This is necessary because the make
and model
instance variables are declared as protected
in the Vehicle
class, which means they can only be accessed by subclasses.
Now, we can create instances of the Car
class and call its methods:
Car myCar = new Car("Toyota", "Corolla", 4);
myCar.start();
myCar.drive();
myCar.stop();
This code creates a new Car
object with the make "Toyota", model "Corolla", and 4 doors. We can call the start()
, drive()
, and stop()
methods on this object, which will call the corresponding methods in the Vehicle
class.
In summary, inheritance is a mechanism in Java that allows a subclass to inherit properties and behaviors from a superclass. The subclass can add new properties and behaviors and override or extend the ones inherited from the superclass.
Comments