Java Inheritance

Java Inheritance is a fundamental concept in object-oriented programming that allows a new class to inherit properties and behaviors (fields and methods) from an existing class. This promotes code reusability and establishes a hierarchical relationship between classes.

Key Concepts

  1. Superclass (Parent Class): The class whose properties and methods are inherited.
  2. Subclass (Child Class): The class that inherits from the superclass.

Usage
Inheritance is used to create a new class that is a type of an existing class. It helps in extending the functionality of a class without modifying it, thereby adhering to the Open/Closed Principle of software design.

Syntax

class Superclass {
    // fields and methods
}

class Subclass extends Superclass {
    // additional fields and methods
}

Examples
Example 1: Basic Inheritance

class Animal {
    void eat() {
        System.out.println("This animal eats food.");
    }
}

class Dog extends Animal {
    void bark() {
        System.out.println("The dog barks.");
    }
}

public class InheritanceExample {
    public static void main(String[] args) {
        Dog dog = new Dog();
        dog.eat();  // Inherited method
        dog.bark(); // Subclass method
    }
}

In this example, Dog is a subclass that inherits the eat method from the Animal superclass. The Dog class also has its own method, bark.

Example 2: Overriding Methods

class Vehicle {
    void run() {
        System.out.println("The vehicle is running.");
    }
}

class Car extends Vehicle {
    @Override
    void run() {
        System.out.println("The car is running safely.");
    }
}

public class MethodOverridingExample {
    public static void main(String[] args) {
        Car car = new Car();
        car.run(); // Overridden method
    }
}

Here, the Car class overrides the run method of the Vehicle class to provide a specific implementation.

Example 3: Using super Keyword

class Person {
    String name = "John";

    void display() {
        System.out.println("Person's name: " + name);
    }
}

class Employee extends Person {
    String name = "Doe";

    void display() {
        System.out.println("Employee's name: " + name);
        super.display(); // Call superclass method
    }
}

public class SuperKeywordExample {
    public static void main(String[] args) {
        Employee emp = new Employee();
        emp.display();
    }
}

In this example, the super keyword is used to call the display method of the superclass Person from the subclass Employee.

Method Overriding in Java

If subclass (child class) has the same method as declared in the parent class, it is known as method overriding in Java.

In other words, If a subclass provides the specific implementation of the method that has been declared by one of its parent class, it is known as method overriding.

Reference link:
https://www.datacamp.com/doc/java/inheritance