Cosmic Module

J

Qubits of DPK

March 14, 2026

Core Java

Layman Explanation

A child inherits features from parents — eye color, height, surname. In Java, a child class inherits fields and methods from its parent class. No need to rewrite what already exists.

Real World Analogy

All vehicles have wheels, engine, fuel. A Car IS a vehicle. A Truck IS a vehicle. Instead of writing wheels/engine for every vehicle type separately — define it ONCE in Vehicle, inherit everywhere.

What is Inheritance?

A mechanism where one class (child/subclass) acquires the properties and methods of another class (parent/superclass).
java
QUBITS OF DPK
1class Vehicle {
2    String brand;
3    int speed;
4
5    void accelerate() {
6        speed += 10;
7        System.out.println(brand + " accelerating. Speed: " + speed);
8    }
9}
10
11class Car extends Vehicle {   // Car inherits from Vehicle
12    int numberOfDoors;
13
14    void openTrunk() {
15        System.out.println("Trunk opened!");
16    }
17}
18
19Car myCar = new Car();
20myCar.brand = "Toyota";   // inherited from Vehicle
21myCar.accelerate();        // inherited method
22myCar.openTrunk();         // Car's own method

Types of Inheritance

1. Single Inheritance

javascript
QUBITS OF DPK
1VehicleCar
2One parent, one child

2. Multilevel Inheritance

javascript
QUBITS OF DPK
1AnimalDogLabrador
2Chain of inheritance
java
QUBITS OF DPK
1class Animal {
2    void eat() { System.out.println("Eating"); }
3}
4
5class Dog extends Animal {
6    void bark() { System.out.println("Barking"); }
7}
8
9class Labrador extends Dog {
10    void fetch() { System.out.println("Fetching"); }
11}
12
13Labrador lab = new Labrador();
14lab.eat();    // from Animal
15lab.bark();   // from Dog
16lab.fetch();  // own method

3. Hierarchical Inheritance

javascript
QUBITS OF DPK
1        Animal
2       /      \
3     Dog      Cat
4One parent, multiple children

4. Multiple Inheritance — NOT supported directly

java
QUBITS OF DPK
1// Java doesn't allow:
2class C extends A, B { }  // ❌ compile error!
Why? Diamond Problem:
javascript
QUBITS OF DPK
1     A
2    / \
3   B   C
4    \ /
5     D
6// If A has method fly(), B and C both override it
7// Which fly() does D inherit? Ambiguous!
Java's Solution: Use Interfaces for multiple inheritance.

super Keyword

java
QUBITS OF DPK
1class Animal {
2    String name = "Animal";
3
4    void makeSound() {
5        System.out.println("Some sound");
6    }
7}
8
9class Dog extends Animal {
10    String name = "Dog";
11
12    void display() {
13        System.out.println(name);         // Dog (own field)
14        System.out.println(super.name);   // Animal (parent field)
15    }
16
17    void makeSound() {
18        super.makeSound();                // calls parent method
19        System.out.println("Woof!");
20    }
21}

super() — Call Parent Constructor

java
QUBITS OF DPK
1class Animal {
2    String name;
3    Animal(String name) { this.name = name; }
4}
5
6class Dog extends Animal {
7    String breed;
8
9    Dog(String name, String breed) {
10        super(name);        // MUST be first line!
11        this.breed = breed;
12    }
13}

Method Overriding

Child class provides its own implementation of a method inherited from parent.
java
QUBITS OF DPK
1class Animal {
2    void makeSound() {
3        System.out.println("Some generic sound");
4    }
5}
6
7class Dog extends Animal {
8    @Override
9    void makeSound() {              // overrides parent
10        System.out.println("Woof!");
11    }
12}
13
14class Cat extends Animal {
15    @Override
16    void makeSound() {
17        System.out.println("Meow!");
18    }
19}
20
21Animal a = new Dog();
22a.makeSound();   // Woof! (runtime decides)

Overriding Rules

javascript
QUBITS OF DPK
11. Same method name, same parameters, same return type
22. Cannot override: static, final, private methods
33. Access modifier can be same or MORE permissive
44. @Override annotation — always use it (catches errors!)

Overriding vs Overloading

Packages & Access Modifiers

Packages

java
QUBITS OF DPK
1package com.deepak.banking;   // declares package
2import java.util.ArrayList;   // imports from other package

Access Modifiers

java
QUBITS OF DPK
1public class Student {           // visible everywhere
2    private int age;             // only within class
3    protected String name;       // class + package + subclass
4    double cgpa;                 // default: class + package
5}

️ All Traps

java
QUBITS OF DPK
1// Trap 1 — super() must be first in constructor
2Dog(String name) {
3    breed = "Lab";   // ❌ super() must come first!
4    super(name);
5}
6
7// Trap 2 — Cannot override static methods
8// Static methods are HIDDEN not overridden
9class Parent { static void show() { } }
10class Child extends Parent { static void show() { } }  // hiding, not overriding!
11
12// Trap 3 — Cannot override final methods
13class Parent { final void show() { } }
14class Child extends Parent {
15    void show() { }  // ❌ compile error!
16}
17
18// Trap 4 — Multiple inheritance not allowed via classes
19class C extends A, B { }  // ❌
20
21// Trap 5 — @Override catches mistakes
22class Dog extends Animal {
23    void makeSoun() { }  // ⚠️ typo — no error without @Override!
24    @Override
25    void makeSoun() { }  // ❌ compiler catches: no such method in Animal
26}

Interview Answer (SDE-2)

"Inheritance allows a child class to acquire fields and methods from a parent class via the 'extends' keyword, promoting code reuse. Java supports single, multilevel, and hierarchical inheritance. Multiple inheritance via classes is not supported due to the diamond problem — interfaces solve this. 'super' accesses parent members and super() calls parent constructor (must be first line). Method overriding lets child redefine parent methods — resolved at runtime (dynamic polymorphism). Always use @Override annotation to catch typos. Access modifiers control visibility: private < default < protected < public."

Interview Questions & MAANG-Level Answers

Q1. What is inheritance and what problem does it solve?
Inheritance allows a child class to acquire fields and methods from a parent class via extends. Problem it solves: code reuse and avoiding duplication. Without inheritance: every Vehicle subtype (Car, Truck, Bike) would duplicate start(), stop(), fuelLevel etc. With inheritance: define once in Vehicle, all subtypes inherit. Also enables polymorphism — Vehicle v = new Car() — write generic code that works for all subtypes.
Q2. Why doesn't Java support multiple inheritance with classes?
Because of the diamond problem. If class C extends both A and B, and both A and B override method fly() from a common parent, then C inherits two conflicting implementations of fly() — ambiguous. Java resolves this by only allowing single class inheritance. Multiple inheritance is supported through interfaces where Java 8+ requires you to explicitly override conflicting default methods.
Q3. What is the diamond problem?
javascript
QUBITS OF DPK
1  A (fly())
2 / \
3B   C   (both override fly())
4 \ /
5  D   (inherits from B and C — which fly()??)
D inheriting from both B and C creates ambiguity about which fly() implementation D gets. Java prevents this by disallowing class D extends B, C. With interfaces: if B and C are interfaces with default fly(), class D must explicitly override fly() and can use B.super.fly() to call a specific one.
Q4. What is the difference between method overloading and overriding?
Overloading: same class, same method name, DIFFERENT parameters — compile-time resolution (static polymorphism). Overriding: parent+child class, same name, SAME parameters — runtime resolution (dynamic polymorphism). Return type alone doesn't make overloading. Access modifier must be same or more permissive in override. @Override is mandatory annotation for overriding (catches typos). Static methods are hidden not overridden.
Q5. What is super() and what rule applies to it?
super() calls the parent class constructor from child constructor. Rule: must be the FIRST statement. If not explicitly written, Java implicitly inserts super() (no-arg parent constructor call). If parent has no no-arg constructor, you MUST explicitly call the correct super(args). super.method() calls parent's version of an overridden method. super.field accesses parent's field when child has same name.
Q6. What is the difference between protected and default access?
Default (no modifier): accessible within the same package only — subclasses in DIFFERENT packages cannot access it. Protected: accessible within same package AND in subclasses regardless of package. Example: if Vehicle.fuelType is protected, a Car class in a different package can access it. If it were default, it couldn't. In practice, use protected for "designed for inheritance" members.
Q7. Can you override a private method? Why or why not?
No. Private methods are not visible to child classes — they can't be inherited, so they can't be overridden. If a child class defines a method with the same name/signature as a parent's private method, it's a completely new method in the child class, not an override. @Override on it would cause a compile error. This is why you can't access private methods via polymorphism.
Q8. What does @Override annotation do?
@Override tells the compiler to verify that this method actually overrides a method from a superclass or interface. If the method doesn't match any parent method (wrong name spelling, wrong parameter type), the compiler throws an error. Without @Override, a typo like makeSound() vs makeSoud() would compile silently as a new method — the override never happens, causing subtle runtime bugs. Always use @Override when overriding.