Java - OOP - Inheritance - Single
Single Inheritance is a type of inheritance in Java in which a derived class (also called child or subclass) inherits properties and behavior of a single parent class. This means that the child class is a specialized version of the parent class, and can have additional properties and behavior of its own. Single Inheritance is a fundamental concept in Object-Oriented Programming (OOP) and is used extensively in Java.
Let's take an example to understand Single Inheritance in Java:
Suppose we have a parent class called "Vehicle" that has some basic properties and behavior related to all types of vehicles. The child class "Car" can inherit these basic properties and behavior from the Vehicle class and add some additional properties and behavior related to cars.
Here's how we can implement Single Inheritance in Java:
// Parent class
class Vehicle {
String type;
int wheels;
void start() {
System.out.println("Starting vehicle...");
}
void stop() {
System.out.println("Stopping vehicle...");
}
}
// Child class
class Car extends Vehicle {
String brand;
String model;
void accelerate() {
System.out.println("Accelerating...");
}
void brake() {
System.out.println("Applying brakes...");
}
}
In the above example, the parent class "Vehicle" has two properties: "type" and "wheels", and two methods: "start()" and "stop()". The child class "Car" inherits these properties and methods from the parent class and adds two additional properties: "brand" and "model", and two methods: "accelerate()" and "brake()".
Now, we can create an object of the Car class and access the properties and methods of both the parent and child classes:
Car car1 = new Car();
car1.type = "Four-wheeler";
car1.wheels = 4;
car1.brand = "Toyota";
car1.model = "Camry";
car1.start();
car1.accelerate();
car1.brake();
car1.stop();
In the above code, we create an object "car1" of the "Car" class and set its properties. We can also access the methods of both the parent and child classes using the object.
Single Inheritance provides a way to reuse the code from the parent class in the child class and allows us to create specialized versions of the parent class. It also helps to reduce the code duplication and improves the code maintainability.