Inheritance
In object-oriented design, inheritance is a mechanism that allows one class to inherit the properties and behaviors of another class. The class that inherits is called the child class or subclass, and the class being inherited from is called the parent class or superclass.
Inheritance facilitates code reuse and maintainability by allowing us to define common attributes and methods in a parent class and have them automatically available in the child class.
Let's consider the example of a Vehicle
class and a Car
class that inherits from it:
1class Vehicle {
2 protected String brand;
3 protected int year;
4
5 public Vehicle(String brand, int year) {
6 this.brand = brand;
7 this.year = year;
8 }
9
10 public void start() {
11 System.out.println("Starting the vehicle...");
12 }
13}
14
15class Car extends Vehicle {
16 private int numOfDoors;
17
18 public Car(String brand, int year, int numOfDoors) {
19 super(brand, year);
20 this.numOfDoors = numOfDoors;
21 }
22
23 public void drive() {
24 System.out.println("Driving the car...");
25 }
26}
27
28public class Main {
29 public static void main(String[] args) {
30 Car myCar = new Car("Toyota", 2021, 4);
31 myCar.start();
32 myCar.drive();
33 }
34}
In this example, the Vehicle
class serves as the parent class, and the Car
class inherits from it. The Car
class extends the Vehicle
class using the extends
keyword.
The Vehicle
class has properties such as brand
and year
, as well as a method start()
.
The Car
class adds an additional property numOfDoors
and a method drive()
. It can also access the properties and methods defined in the Vehicle
class using the super
keyword.
By creating an instance of the Car
class and calling its methods, we can see the inheritance in action. The output of the above code will be:
1Starting the vehicle...
2Driving the car...
In summary, inheritance allows classes to inherit properties and behaviors from other classes, facilitating code reuse and maintainability.
xxxxxxxxxx
}
class Vehicle {
protected String brand;
protected int year;
public Vehicle(String brand, int year) {
this.brand = brand;
this.year = year;
}
public void start() {
System.out.println("Starting the vehicle...");
}
}
class Car extends Vehicle {
private int numOfDoors;
public Car(String brand, int year, int numOfDoors) {
super(brand, year);
this.numOfDoors = numOfDoors;
}
public void drive() {
System.out.println("Driving the car...");
}
}
class Main {
public static void main(String[] args) {