KTU OOP Java2024 Scheme • 60M ESE
MODULE 2/Section 2: Inheritance

Inheritance Fundamentals, extends & Types of Inheritance (incl. Multiple/Hybrid Limitations)

HIGH PRIORITY (Prep Guide)Official Syllabus~16 min study
Official KTU 2024 Syllabus Topics Covered Here
Introduction to inheritanceSuperclass and subclassextends keywordTypes of inheritanceSingle inheritanceMultilevel inheritanceHierarchical inheritanceMultiple inheritance and Java's limitationsHybrid inheritance and Java's implementation limitations

1. Topic Introduction

Why rewrite name, age, and displayBasicInfo() separately inside Student, Teacher, and Doctor? Inheritance lets you place shared traits in a general Superclass (Person) and create specialized Subclasses (Student extends Person) that automatically inherit those members and add only what is unique—creating clean hierarchical classifications.

2. Start From Zero: Basic Smartphone Blueprint Inherited by Pro & Gaming Models

A manufacturer creates a solid BasicPhone blueprint (call, SMS, battery). When building CameraPhone, engineers don't redesign calling from scratch—they say CameraPhone extends BasicPhone and add ONLY the lens! Notice two rules: (1) BasicPhone still works completely on its own as a stand-alone class, and (2) Java intentionally forbids a class from having TWO parent classes at once (class Hybrid extends Phone, Tablet is banned!) because if both parents define turnOn(), Java wouldn't know which parent's body to inherit (the Diamond Problem).

Key Takeaway: Java classes support Single, Multilevel, and Hierarchical inheritance via extends. Multiple & Hybrid class inheritance are disallowed to avoid ambiguity—achieved instead using Interfaces (implements).

3. Essential Exam Definitions

Superclass (Base / Parent Class)
A general class whose common attributes and methods are inherited by one or more derived classes.
Subclass (Derived / Child Class)
A specialized class declared with extends SuperClass that inherits accessible members of the superclass and adds or overrides specialized members.
The Diamond Problem (Multiple Inheritance Ambiguity)
Ambiguity arising when a subclass inherits from two superclasses that both inherit from a common ancestor or define conflicting implementations of the same method (show()).

4. Detailed Technical Explanation & Syntax

1. Superclass, Subclass & Member Access Rules

Syntax: class SubClass extends SuperClass { ... }. Notice that even when A acts as a superclass for B, A remains an independent stand-alone class that can be instantiated directly.

Member Visibility Rule: A subclass inherits non-private fields and methods, **EXCEPT private members**. A private member remains strictly private to its own class—NOT accessible directly even by its subclasses! (Note: constructors are NOT inherited either—they are invoked via super()).

2. Types of Inheritance in Java

Five standard inheritance patterns appear in OOP theory—know which 3 work with Java classes and why 2 are restricted:

  • 1. Single Inheritance (Supported): One subclass extends one superclass (class B extends A).
  • 2. Multilevel Inheritance (Supported): A subclass acts as a superclass for another subclass (Box -> BoxWeight -> Shipment). Each level inherits traits from ALL ancestors above it.
  • 3. Hierarchical Inheritance (Supported): One superclass is extended by multiple specialized subclasses (Person -> Student, Person -> Teacher, Person -> Doctor).
  • 4. Multiple Inheritance (NOT supported for classes): A class CANNOT extends more than one class (class C extends A, B is a COMPILE ERROR) to eliminate the Diamond Problem and keep constructor chaining unambiguous. Achieved via Interfaces (class C implements I1, I2).
  • 5. Hybrid Inheritance (NOT supported via classes alone): A combination involving multiple class parents (e.g., diamond A -> B, C -> D) is disallowed for classes, though hybrid combinations using class + multiple interfaces (class D extends B implements I1, I2) ARE valid!

5. Working Principle: Why Superclass ref = new Subclass() Works in Java

  1. Every BoxWeight object contains ALL fields of Box plus weight.
  2. Therefore, a Box reference variable (Box plainBox = new BoxWeight(...)) can legally point to a BoxWeight object—because a BoxWeight IS-A Box!
  3. Crucial Restriction: Through plainBox, the compiler ONLY permits accessing members defined in Box (NOT plainBox.weight), because the reference type limits compile-time visibility!

6. Examination-Ready Diagrams

Diagram 5

Types of Inheritance in Java

1. SingleClass AClass B2. MultilevelBoxBoxWeightShipment3. HierarchicalPersonStudentTeacher4. Multiple (Interface Only)<<int>> A<<int>> BClass Cimplements A, BClass C extends A, BILLEGAL (Diamond Ambiguity)Arrows point from Subclass to Superclass (extends = solid, implements = dashed)

Comparison of Single, Multilevel, and Hierarchical inheritance supported by Java classes, alongside Multiple and Hybrid inheritance (disallowed for classes, achieved via interfaces).

Key Components
  • Single Inheritance: Class B extends Class A (A -> B).
  • Multilevel Inheritance: Chain of derivation (A -> B -> C).
  • Hierarchical Inheritance: Multiple subclasses extend one superclass (A -> B, A -> C, A -> D).
  • Multiple / Hybrid (Via Interfaces): A class cannot extend two classes (Diamond Problem), so it implements multiple interfaces.
Step-by-Step Flow
  1. Arrow points from subclass to superclass (or top-down hierarchy labeled extends).
  2. Single: one parent, one child.
  3. Multilevel: child becomes parent for grandchild (Box -> BoxWeight -> Shipment).
  4. Hierarchical: one parent (Person), multiple specialized children (Student, Teacher).
  5. Multiple class inheritance causes ambiguity if both parents define the same method; Java solves this with Interfaces.
How to Draw in KTU Exam
  • Draw 5 mini trees side-by-side: Single (A -> B), Multilevel (A -> B -> C), Hierarchical (A -> B, C), Multiple (crossed out for classes, dashed implements arrows for interfaces), Hybrid (combination).
  • Always indicate UML inheritance arrows or clear extends labels so direction is unambiguous.

7. Complete Java Code Examples & Tracing

Single, Hierarchical & Superclass-to-Subclass Reference RuleInheritanceTypesDemo.java
Demonstrates Hierarchical inheritance (Person -> Student, Teacher), private-field encapsulation, and superclass reference holding subclass object.
1class Person {
2 String name;
3 private String secretId = "CONFIDENTIAL"; // NOT directly visible in subclasses!
4
5 Person(String name) {
6 this.name = name;
7 }
8
9 void showPerson() {
10 System.out.println("Person: " + name + " (" + secretId + ")");
11 }
12}
13
14class Student extends Person {
15 int rollNo;
16
17 Student(String name, int rollNo) {
18 super(name);
19 this.rollNo = rollNo;
20 }
21
22 void showStudent() {
23 System.out.println("Student: " + name + ", Roll: " + rollNo);
24 // System.out.println(secretId); // ILLEGAL: private to Person!
25 }
26}
27
28class Teacher extends Person {
29 String department;
30
31 Teacher(String name, String department) {
32 super(name);
33 this.department = department;
34 }
35}
36
37public class InheritanceTypesDemo {
38 public static void main(String[] args) {
39 Student s = new Student("Neha", 24);
40 Teacher t = new Teacher("Prof. Nair", "CSE");
41 s.showStudent();
42 System.out.println("Teacher: " + t.name + " - " + t.department);
43
44 // Superclass variable referencing a Subclass object
45 Person pRef = s;
46 pRef.showPerson(); // Valid: defined in Person
47 // System.out.println(pRef.rollNo); // ILLEGAL: Person ref cannot see rollNo!
48 }
49}
Expected Output
Student: Neha, Roll: 24
Teacher: Prof. Nair - CSE
Person: Neha (CONFIDENTIAL)
Keywords:extendsprivatesuperclass
Common Exam & Coding Mistakes
  • Writing class C extends A, B expecting multiple class inheritance (compile error!).
  • Trying to access a superclass private field directly in a subclass.
  • Assuming a superclass reference pRef can directly read subclass-only fields like pRef.rollNo.

Advantages

  • Eliminates duplicate code across related classes.
  • Establishes clean IS-A taxonomy and enables runtime polymorphism.

Limitations / Disadvantages

  • Tightly couples subclass implementation to parent class changes.
  • Deep inheritance hierarchies can become harder to trace than composition.

Real-World Applications

  • Swing UI hierarchy (Component -> Container -> JComponent -> AbstractButton -> JButton).
  • Java Exception tree (Object -> Throwable -> Exception -> IOException).

Important KTU Exam Points

  • Always draw Diagram 5 (Single, Multilevel, Hierarchical vs Multiple/Hybrid crossed out for classes + allowed via Interfaces).
  • Explicitly state WHY Java omits multiple class inheritance (Diamond ambiguity & complexity).
  • Always mention that private members of a superclass are NOT accessible in subclasses.

Memory Techniques & Revision

  • Class Inheritance Allowed — 'S-M-H': Single, Multilevel, Hierarchical (classes). Multiple & Hybrid need Interfaces!

Common Pitfalls to Avoid

  • Forgetting that Object (java.lang.Object) is the implicit ultimate superclass of every Java class that lacks an explicit extends clause!

KTU-Style Questions & Exam-Ready Answers

Structured specifically for KTU Part A (3-mark) and Part B (6/9-mark) evaluation rubrics.

Introduction: Inheritance allows a subclass (extends) to acquire fields and methods of a superclass, promoting code reuse and hierarchical modeling.

  • 1. Single Inheritance: One subclass inherits one superclass (class B extends A).
  • 2. Multilevel Inheritance: Chain of subclasses (Box -> BoxWeight -> Shipment).
  • 3. Hierarchical Inheritance: Multiple subclasses inherit one common superclass (Person -> Student, Teacher).
  • 4. Multiple & Hybrid Limitations: Java prohibits class C extends A, B to avoid the Diamond Problem (method/constructor ambiguity when two parents define the same method or share an ancestor) and reduce complexity.
  • 5. Java's Solution: A class can implements multiple interfaces (class C implements I1, I2), achieving safe multiple inheritance of type.
Exam Diagram Note: Reproduce Diagram 5 showing all 5 trees with extends vs implements clearly labeled.

Quick Understanding Check

1. Which types of inheritance can be implemented in Java using ONLY classes (extends)?