Inheritance
Inheritance in Java is a fundamental concept of Object-Oriented Programming (OOP) that allows a
new class (called the subclass or child class) to inherit properties and behaviors (fields and methods)
from an existing class (called the superclass or parent class). This promotes code reusability and
helps in establishing a relationship between different classes.
Key Points:
1. Superclass (Parent class): The class whose properties and methods are inherited.
2. Subclass (Child class): The class that inherits the properties and methods from the
superclass.
3. extends keyword: Used to declare inheritance in Java.
// Superclass (Parent class)
class Vehicle {
// Field
String brand;
// Constructor
public Vehicle(String brand) {
this.brand = brand;
// Method
public void startEngine() {
System.out.println("The engine is starting...");
// Subclass (Child class)
class Car extends Vehicle {
// Constructor of the Car class
public Car(String brand) {
// Calling the constructor of the superclass (Vehicle)
super(brand);
// Method specific to the Car class
public void honk() {
System.out.println("The car horn goes beep beep!");
public class Main {
public static void main(String[] args) {
// Creating an object of the Car class
Car myCar = new Car("Toyota");
// Accessing the inherited field and method from Vehicle
System.out.println("Car brand: " + myCar.brand);
myCar.startEngine(); // Inherited method from Vehicle
// Calling the Car-specific method
myCar.honk(); // Method specific to the Car class