×

Advanced Coding & Software Engineering Program

Duration: 1 Year (12 Months)

Join our premium 1-year program to master cutting-edge technologies and become an industry-ready Software Engineer!

Course Coverage

  • Languages: C, C++, Java, JavaScript, Python
  • Web Technologies: HTML, CSS, Bootstrap 5, MERN Stack, Full Stack Development
  • Databases: MySQL, MongoDB
  • Data Science Libraries: Pandas, NumPy
  • Development Tools: Visual Studio Code, IntelliJ IDEA, PyCharm, Postman, Git, GitHub
  • Cloud Platforms: Vercel, MongoDB Atlas

Program Highlights

  • Live Classes: Interactive sessions with real-time doubt resolution
  • Hands-On Sessions: Practical coding exercises to build real-world skills
  • Industry Experts: Learn from professionals with years of experience
  • Live Project: Work on real-world projects to apply your skills
  • Get Certificate: Earn a professional certificate upon program completion

Course Fee: Only ₹1020 / month
Limited Period Offer!

Java Inheritance Tutorial for Beginners



Last Updated on: 12th Nov 2025 11:07:29 AM

Welcome to this beginner-friendly tutorial on Inheritance in Java! Inheritance is one of the most important concepts in Object-Oriented Programming (OOP). It allows one class (called the subclass or child class) to inherit properties and behaviors (fields and methods) from another class (called the superclass or parent class). This promotes code reusability, modularity, and real-world modeling.

This tutorial explains inheritance in simple terms with full explanations, real-time project-based examples, and runnable code. No tables — just clear, step-by-step learning. Let’s get started!

 

What is Inheritance?

Inheritance is a mechanism where a new class inherits the properties (fields) and behaviors (methods) of an existing class.

  • The superclass (parent) contains common features.

  • The subclass (child) extends the superclass and can:

    • Reuse the parent’s code.

    • Add new features.

    • Override (modify) parent methods.

 

Real-World Analogy:
Think of a Payment System in an e-commerce app. A Payment (parent) has common features like process() and getAmount(). Then CreditCardPayment, PayPalPayment, and BankTransferPayment (children) inherit and add their own logic.

 

Why use inheritance?

  1. For Method Overriding (so runtime polymorphism can be achieved).

  2. For Code Reusability.

 

The extends Keyword

To create inheritance in Java, use the extends keyword:

class SubclassName extends SuperclassName {
    // subclass code
}

 

Types of Inheritance in Java

Java supports 5 types of inheritance. Let’s list them clearly:

  1. Single Inheritance

  2. Multilevel Inheritance

  3. Hierarchical Inheritance

  4. Multiple Inheritance (via interfaces only, not classes)

  5. Hybrid Inheritance (combination of above)

 

Note: Java does NOT support Multiple Inheritance through classes to avoid ambiguity (the "Diamond Problem"). But it supports it via interfaces.

 

Let’s explore each type with real-time project-based examples.

 

1. Single Inheritance

When a class inherits another class, it is known as a single inheritance. In the example given below, CreditCardPayment class inherits the Payment class, so there is single inheritance.

Real-Time Project Example: E-Commerce Payment Gateway

// Superclass - Common payment logic
class Payment {
    double amount;
    String transactionId;

    void process() {
        System.out.println("Processing payment of ₹" + amount);
    }

    void generateReceipt() {
        System.out.println("Receipt generated for Transaction: " + transactionId);
    }
}

// Subclass - Specific to Credit Card
class CreditCardPayment extends Payment {
    String cardNumber;
    String cardHolderName;

    void validateCard() {
        System.out.println("Validating card: **** **** **** " + cardNumber.substring(12));
    }

    @Override
    void process() {
        validateCard();
        super.process(); // Reuse parent logic
        System.out.println("Paid via Credit Card by " + cardHolderName);
    }
}

public class SingleInheritanceExample {
    public static void main(String[] args) {
        CreditCardPayment cc = new CreditCardPayment();
        cc.amount = 2500.00;
        cc.transactionId = "TXN12345";
        cc.cardNumber = "1234567890123456";
        cc.cardHolderName = "Amit Sharma";

        cc.process();        // Uses overridden method
        cc.generateReceipt(); // Inherited from Payment
    }
}

 

Output:

Validating card: **** **** **** 3456
Processing payment of ₹2500.0
Paid via Credit Card by Amit Sharma
Receipt generated for Transaction: TXN12345

 

Explanation:
CreditCardPayment inherits processPayment() from Payment and adds card-specific logic. This is single inheritance.

 

Project Use Case:
In a real e-commerce app, all payment types share common logic (process, receipt), but each has unique validation.

 

2. Multilevel Inheritance

When a derived class inherits another derived class, it is known as multilevel inheritance. In the example below, GoldMembership inherits PremiumMembership, which inherits Membership, forming a chain.

Real-Time Project Example: Subscription Management System

class Membership {
    String userEmail;
    void sendWelcomeEmail() {
        System.out.println("Welcome email sent to " + userEmail);
    }
}

class PremiumMembership extends Membership {
    int adFreeAccess = 1;
    void enableAdFree() {
        System.out.println("Ad-free experience enabled for " + userEmail);
    }
}

class GoldMembership extends PremiumMembership {
    int prioritySupport = 1;
    void enablePrioritySupport() {
        System.out.println("24/7 Priority Support activated for " + userEmail);
    }
}

public class MultilevelExample {
    public static void main(String[] args) {
        GoldMembership gold = new GoldMembership();
        gold.userEmail = "vip@company.com";

        gold.sendWelcomeEmail();     // From Membership
        gold.enableAdFree();         // From PremiumMembership
        gold.enablePrioritySupport(); // From GoldMembership
    }
}

 

Output:

Welcome email sent to vip@company.com
Ad-free experience enabled for vip@company.com
24/7 Priority Support activated for vip@company.com

 

Project Use Case:
In Netflix/Spotify-like apps, membership tiers build on each other: Free → Premium → Gold.

 

3. Hierarchical Inheritance

When multiple classes inherit from a single class, it is known as hierarchical inheritance. In the example below, EmailNotification, SMSNotification, and PushNotification all inherit from Notification.

Real-Time Project Example: Notification Service in a Banking App

class Notification {
    String recipient;
    String message;

    void send() {
        System.out.println("Sending notification to: " + recipient);
    }
}

class EmailNotification extends Notification {
    String subject;

    @Override
    void send() {
        System.out.println("EMAIL ? To: " + recipient + " | Subject: " + subject);
        System.out.println("Body: " + message);
    }
}

class SMSNotification extends Notification {
    @Override
    void send() {
        System.out.println("SMS ? To: " + recipient);
        System.out.println("Message: " + message);
    }
}

class PushNotification extends Notification {
    String appName = "MyBank";

    @Override
    void send() {
        System.out.println("PUSH ? App: " + appName + " | User: " + recipient);
        System.out.println("Alert: " + message);
    }
}

public class HierarchicalExample {
    public static void main(String[] args) {
        EmailNotification email = new EmailNotification();
        SMSNotification sms = new SMSNotification();
        PushNotification push = new PushNotification();

        email.recipient = "user@example.com";
        email.subject = "Transaction Alert";
        email.message = "₹5000 debited from your account.";
        email.send();

        sms.recipient = "+919876543210";
        sms.message = "OTP: 123456";
        sms.send();

        push.recipient = "DeviceID_789";
        push.message = "Login from new device";
        push.send();
    }
}

 

Output:

EMAIL ? To: user@example.com | Subject: Transaction Alert
Body: ₹5000 debited from your account.
SMS ? To: +919876543210
Message: OTP: 123456
PUSH ? App: MyBank | User: DeviceID_789
Alert: Login from new device

 

Project Use Case:
In banking or e-commerce apps, one Notification system sends alerts via multiple channels.

 

4. Multiple Inheritance (via Interfaces)

When a class implements multiple interfaces, it achieves multiple inheritance. Java doesn’t allow a class to extend multiple classes, but interfaces solve this.

Real-Time Project Example: Smart Home Device Controller

interface WiFiConnectable {
    void connectToWiFi(String ssid);
}

interface BluetoothPairable {
    void pairWithDevice(String deviceName);
}

interface VoiceControllable {
    void listenToVoiceCommand(String command);
}

class SmartBulb implements WiFiConnectable, BluetoothPairable, VoiceControllable {
    String bulbId;

    public void connectToWiFi(String ssid) {
        System.out.println("Bulb " + bulbId + " connected to WiFi: " + ssid);
    }

    public void pairWithDevice(String deviceName) {
        System.out.println("Bulb paired with " + deviceName + " via Bluetooth");
    }

    public void listenToVoiceCommand(String command) {
        if (command.toLowerCase().contains("on")) {
            System.out.println("Bulb ON");
        } else if (command.toLowerCase().contains("off")) {
            System.out.println("Bulb OFF");
        }
    }
}

public class MultipleInheritanceExample {
    public static void main(String[] args) {
        SmartBulb bulb = new SmartBulb();
        bulb.bulbId = "BULB-001";

        bulb.connectToWiFi("HomeNetwork");
        bulb.pairWithDevice("Alexa");
        bulb.listenToVoiceCommand("Turn on the light");
    }
}

 

Output:

Bulb BULB-001 connected to WiFi: HomeNetwork
Bulb paired with Alexa via Bluetooth
Bulb ON

 

Project Use Case:
In IoT/smart home apps, devices support multiple protocols (WiFi, Bluetooth, Voice).

 

5. Hybrid Inheritance

When a combination of two or more types of inheritance is used, it is known as hybrid inheritance. In the example below, we combine hierarchical and multilevel inheritance in a Hospital Management System.

Real-Time Project Example: Hospital Management System

// Base class
class Person {
    String name;
    int age;

    void displayInfo() {
        System.out.println("Name: " + name + ", Age: " + age);
    }
}

// Hierarchical: Doctor and Patient inherit from Person
class Doctor extends Person {
    String specialization;
    void prescribe() {
        System.out.println("Dr. " + name + " prescribing medicine...");
    }
}

class Patient extends Person {
    String disease;
    void admit() {
        System.out.println("Patient " + name + " admitted.");
    }
}

// Multilevel: SeniorDoctor inherits from Doctor
class SeniorDoctor extends Doctor {
    int experienceYears;

    void performSurgery() {
        System.out.println("Senior Dr. " + name + " performing surgery after " + experienceYears + " years.");
    }
}

public class HybridExample {
    public static void main(String[] args) {
        SeniorDoctor srDoc = new SeniorDoctor();
        srDoc.name = "Dr. Rajesh Kumar";
        srDoc.age = 48;
        srDoc.specialization = "Cardiology";
        srDoc.experienceYears = 22;

        srDoc.displayInfo();     // From Person
        srDoc.prescribe();       // From Doctor
        srDoc.performSurgery();  // From SeniorDoctor

        Patient patient = new Patient();
        patient.name = "Priya Singh";
        patient.age = 32;
        patient.disease = "Fever";
        patient.admit();         // From Patient
    }
}

 

 Output:

Name: Dr. Rajesh Kumar, Age: 48
Dr. Rajesh Kumar prescribing medicine...
Senior Dr. Rajesh Kumar performing surgery after 22 years.
Patient Priya Singh admitted.

 

Project Use Case:
In hospital software, Person Doctor/Patient (hierarchical), and Doctor SeniorDoctor (multilevel).

 

Why Java Does NOT Support Multiple Inheritance via Classes?

The Diamond Problem

Imagine this scenario:

class A {
    void show() { System.out.println("A's show"); }
}

class B extends A { }
class C extends A { }

class D extends B, C { } // NOT ALLOWED!

 

Now, if D calls show(), which version should it use? B’s or C’s?

This ambiguity is called the Diamond Problem:

      A
     / \
    B   C
     \ /
      D

 

If both B and C override show(), Java cannot decide which one D should inherit.

Java avoids this confusion by disallowing multiple class inheritance.

Solution: Use interfaces — they only declare methods (no implementation conflict).

 

Method Overriding with super

class Vehicle {
    void start() {
        System.out.println("Vehicle starting...");
    }
}

class ElectricCar extends Vehicle {
    @Override
    void start() {
        super.start(); // Call parent
        System.out.println("Electric motor engaged silently.");
    }
}

 

Key Points Summary

  1. Single Inheritance: One class extends one class → Supported

  2. Multilevel Inheritance: Chain like A → B → C → Supported

  3. Hierarchical Inheritance: One parent, many children → Supported

  4. Multiple Inheritance: Only via interfacesSupported

  5. Hybrid Inheritance: Mix of above → Supported

  • Use @Override for clarity.

  • Use super to access parent members.

  • Java avoids Diamond Problem using interfaces.

 

Practice Tips (Project-Based)

  • Build a Library System: Book EBook, AudioBook (Hierarchical) + PremiumEBook extends EBook (Multilevel).

  • Create Employee Management: Employee Manager, Developer + SeniorDeveloper extends Developer.

 

You now master Inheritance in Java with real-world project examples!
Keep building — this is how enterprise apps are designed. Happy coding! yes


Online - Chat Now
Let’s Connect

Inquiry Sent!

Your message has been successfully sent. We'll get back to you soon!

iKeySkills Logo