We all know that Java is an object-oriented programming language. One of the features of object-oriented programing language is inheritance. Inheritance allows a class to inherit the properties and methods of another class called the parent class. In this blog post, we’ll discuss Java inheritance in detail, including its benefits, how it works.
What is Inheritance in Java?
Inheritance is a key concept in object-oriented programming that enables classes to inherit properties and methods from other classes. It allows for code reuse as well as making it easier to maintain and extend code. In Java, classes can inherit properties and methods from a parent class, which is also known as a superclass or base class. The class that inherits the properties and methods is known as a subclass or derived class.
Benefits of Java Inheritance
The primary benefit of Java inheritance is that it allows for code reuse. By defining common attributes and methods in a superclass, we can avoid duplicating code in multiple subclasses. Additionally, if we need to modify the behavior of a method, we only need to do it in one place: the superclass. The subclasses will automatically inherit the changes.
How Inheritance Works in Java
In Java, we can create a subclass (child class) by extending a superclass (parent class). To extend a class, we use the extends
keyword followed by the name of the superclass (parent class).
Following is an example:
public class Vehicle {
protected int numberOfWheels;
protected String color;
public void start() {
System.out.println("Vehicle started");
}
}
public class Car extends Vehicle {
private String make;
private String model;
public void drive() {
System.out.println("Driving the " + make + " " + model);
}
}
In this example, the Car
class extends the Vehicle
class using the extends
keyword. This means that the Car
class inherits all the properties and methods of the Vehicle
class. Additionally, the Car
class has its own properties and methods that are unique to it.
The Vehicle
class has two properties: numberOfWheels
and color
, and one method: start()
. The Car
class has two additional properties: make
and model
, and one method: drive()
. Since the Car
class extends the Vehicle
class, it can access and modify the properties and methods of the Vehicle
class.