☕ Java — super Keyword

Complete Deep Revision Guide — Hinglish mein samjho, clearly padho | 5 Programs per topic with explanation

📚 Topics

📖

super Kya Hai? — Deep Explanation

this = current class object ka reference super = parent class object ka reference Jab child class object banta hai: HEAP mein: ┌─────────────────────────────────┐ │ CHILD OBJECT │ │ ┌───────────────────────────┐ │ │ │ PARENT PART │ │ │ │ parent variables │ │ ← super refer karta hai! │ │ parent methods │ │ │ ├───────────────────────────┤ │ │ │ CHILD PART │ │ │ │ child variables │ │ ← this refer karta hai! │ │ child methods │ │ │ └───────────────────────────┘ │ └─────────────────────────────────┘ super = us parent part ka reference!
super ke 3 uses: ┌──────────────────┬──────────────────────────────────────┐ │ USE 1 │ super.variable → parent variable │ │ USE 2 │ super.method() → parent method call │ │ USE 3 │ super() → parent constructor │ └──────────────────┴──────────────────────────────────────┘
super Rules — Yaad Rakho: Rule 1: super() sirf CONSTRUCTOR ke andar Normal method mein super() → ERROR! Rule 2: super() HAMESHA FIRST statement Pehle kuch likha → ERROR! Rule 3: super() nahi likha → Compiler AUTOMATICALLY lagata hai Isliye parent ka 0-arg constructor HAMESHA pehle chalta hai Rule 4: super() aur this() ek saath NAHI Ek constructor mein sirf ek allowed! Rule 5: Static method mein super USE NAHI HOTA (Static ka koi object nahi hota)
🔵

USE 1: super.variable — Parent Variable Access 5 Programs

Problem kab aati hai: class Parent { String name = "Parent Name"; ← parent variable } class Child extends Parent { String name = "Child Name"; ← SAME naam! shadows parent! void show() { System.out.println(name); → "Child Name" (local wins!) System.out.println(this.name); → "Child Name" (same) System.out.println(super.name); → "Parent Name" (parent!) } } Jab child mein same naam ka variable ho → child ka variable parent ka "shadow" karta hai! super.variable se parent wala access karo!
Memory mein kya hota hai: Child obj = new Child(); HEAP: ┌────────────────────────────────┐ │ Child Object │ │ ┌────────────────────────────┐ │ │ │ PARENT PART │ │ │ │ name = "Parent Name" ←─────┼─┼── super.name │ ├────────────────────────────┤ │ │ │ CHILD PART │ │ │ │ name = "Child Name" ←─────┼─┼── this.name OR name │ └────────────────────────────┘ │ └────────────────────────────────┘

SuperVariable1.java
public class SuperVariable1 {

    static class Animal {
        String name  = "Animal";
        String sound = "...";
        int    legs  = 0;
    }

    static class Dog extends Animal {
        // Same naam ka variable - shadows parent!
        String name  = "Dog";
        String sound = "Woof";
        int    legs  = 4;

        void showAll() {
            System.out.println("=== Variable Access ===");

            // Without super → child's variable
            System.out.println("name  (child): " + name);
            System.out.println("sound (child): " + sound);
            System.out.println("legs  (child): " + legs);

            System.out.println();

            // With super → parent's variable
            System.out.println("name  (parent): " + super.name);
            System.out.println("sound (parent): " + super.sound);
            System.out.println("legs  (parent): " + super.legs);

            System.out.println();

            // this.variable = same as without super
            System.out.println("this.name  = " + this.name);
            System.out.println("super.name = " + super.name);
        }
    }

    public static void main(String[] args) {
        Dog d = new Dog();
        d.showAll();
    }
}
Output
=== Variable Access === name (child): Dog sound (child): Woof legs (child): 4 name (parent): Animal sound (parent): ... legs (parent): 0 this.name = Dog super.name = Animal
Short Explain: Child mein name, sound, legs — teeno parent ke variables ko "shadow" kar rahe hain. name likhne se child ka milta hai. super.name se parent ka milta hai. Ek object mein DONO versions exist karte hain!

SuperVariable2.java
public class SuperVariable2 {

    static class Vehicle {
        String type     = "Vehicle";
        int    maxSpeed = 100;
        String fuel     = "Petrol";
        double price    = 50000;
    }

    static class Car extends Vehicle {
        String type     = "Car";    // shadows Vehicle.type
        int    maxSpeed = 180;    // shadows Vehicle.maxSpeed
        // fuel - NOT redefined → parent's fuel accessible directly!

        void compare() {
            System.out.println("╔══════════════════════════════╗");
            System.out.println("║   Parent vs Child Variables  ║");
            System.out.println("╠═════════════╦════════════════╣");
            System.out.printf ("║ %-11s ║ %-14s ║%n",
                "VARIABLE", "VALUE");
            System.out.println("╠═════════════╬════════════════╣");

            System.out.printf ("║ type(child) ║ %-14s ║%n", type);
            System.out.printf ("║ type(parent)║ %-14s ║%n", super.type);

            System.out.printf ("║ speed(child)║ %-14d ║%n", maxSpeed);
            System.out.printf ("║ speed(par.) ║ %-14d ║%n", super.maxSpeed);

            // fuel child mein nahi hai → parent ka milega
            System.out.printf ("║ fuel        ║ %-14s ║%n", fuel);

            // price child mein nahi hai → parent ka milega
            System.out.printf ("║ price       ║ Rs.%-11.0f ║%n", super.price);
            System.out.println("╚═════════════╩════════════════╝");
        }
    }

    public static void main(String[] args) {
        Car c = new Car();
        c.compare();
    }
}
Output
╔══════════════════════════════╗ ║ Parent vs Child Variables ║ ╠═════════════╦════════════════╣ ║ VARIABLE ║ VALUE ║ ╠═════════════╬════════════════╣ ║ type(child) ║ Car ║ ║ type(parent)║ Vehicle ║ ║ speed(child)║ 180 ║ ║ speed(par.) ║ 100 ║ ║ fuel ║ Petrol ║ ║ price ║ Rs.50000 ║ ╚═════════════╩════════════════╝
Short Explain: fuel aur price child ne redefine nahi kiya — isliye parent ka hi milega. Sirf jab child same naam se redefine kare tab super zaroori hota hai.

SuperVariable3.java
public class SuperVariable3 {

    static class GrandParent {
        String level = "GrandParent";
        int    value = 100;
    }

    static class Parent extends GrandParent {
        String level = "Parent";   // shadows GrandParent.level
        int    value = 200;        // shadows GrandParent.value
    }

    static class Child extends Parent {
        String level = "Child";    // shadows Parent.level
        int    value = 300;        // shadows Parent.value

        void showLevels() {
            System.out.println("=== 3-Level Variable Access ===");

            // Child ka variable
            System.out.println("level (this):  " + level);
            System.out.println("value (this):  " + value);

            System.out.println();

            // Parent ka variable
            System.out.println("level (super): " + super.level);
            System.out.println("value (super): " + super.value);

            // GrandParent ka directly access possible nahi!
            // super.super.level ← ERROR! Not allowed in Java!
            System.out.println();
            System.out.println("NOTE: super.super NOT allowed in Java!");
            System.out.println("Can only go ONE level up with super");
        }
    }

    public static void main(String[] args) {

        Child c = new Child();
        c.showLevels();

        System.out.println("\n=== Object contains all 3 ===");
        System.out.println("child.level  = " + c.level);
        System.out.println("super = one level up only");
    }
}
Output
=== 3-Level Variable Access === level (this): Child value (this): 300 level (super): Parent value (super): 200 NOTE: super.super NOT allowed in Java! Can only go ONE level up with super === Object contains all 3 === child.level = Child super = one level up only
Short Explain: super sirf EK level upar jaata hai — direct parent ka. Grandparent tak directly super.super se nahi ja sakte — Java mein allowed nahi!

SuperVariable4.java
public class SuperVariable4 {

    // Real-world: Employee with same field names
    static class Person {
        String name    = "Unknown";
        int    age     = 0;
        String address = "Not Set";
    }

    static class Employee extends Person {
        // Employee has its own "name" for display
        String name       = "Employee";  // job title/role
        String department = "General";
        double salary     = 0;

        Employee(String personName, int age,
                 String address, String role,
                 String dept, double salary) {
            // Set parent's variables using super
            super.name    = personName; // ← parent ka name set!
            super.age     = age;
            super.address = address;

            // Set child's variables
            this.name       = role;   // ← child ka name (role)
            this.department = dept;
            this.salary     = salary;
        }

        void displayCard() {
            System.out.println("╔══════════════════════════╗");
            System.out.println("║    EMPLOYEE ID CARD      ║");
            System.out.println("╠══════════════════════════╣");
            System.out.printf ("║ Person: %-17s║%n", super.name);
            System.out.printf ("║ Role:   %-17s║%n", this.name);
            System.out.printf ("║ Age:    %-17d║%n", super.age);
            System.out.printf ("║ Dept:   %-17s║%n", department);
            System.out.printf ("║ Salary: Rs.%-14.0f║%n", salary);
            System.out.printf ("║ Addr:   %-17s║%n", super.address);
            System.out.println("╚══════════════════════════╝");
        }
    }

    public static void main(String[] args) {

        Employee e1 = new Employee(
            "Rahul Sharma", 28, "Delhi",
            "Senior Developer", "IT", 85000);

        Employee e2 = new Employee(
            "Priya Singh", 32, "Mumbai",
            "Team Lead", "Engineering", 120000);

        e1.displayCard();
        System.out.println();
        e2.displayCard();
    }
}
Output
╔══════════════════════════╗ ║ EMPLOYEE ID CARD ║ ╠══════════════════════════╣ ║ Person: Rahul Sharma ║ ║ Role: Senior Developer ║ ║ Age: 28 ║ ║ Dept: IT ║ ║ Salary: Rs.85000 ║ ║ Addr: Delhi ║ ╚══════════════════════════╝ ╔══════════════════════════╗ ║ EMPLOYEE ID CARD ║ ╠══════════════════════════╣ ║ Person: Priya Singh ║ ║ Role: Team Lead ║ ║ Age: 32 ║ ║ Dept: Engineering ║ ║ Salary: Rs.120000 ║ ║ Addr: Mumbai ║ ╚══════════════════════════╝
Short Explain: super.name = personName → parent ka name set kiya. this.name = role → child ka name set kiya. Ek object mein dono alag hain — super.name = actual name, this.name = job role!

SuperVariable5.java
public class SuperVariable5 {

    // Static variable bhi super se access ho sakti hai
    static class Parent {
        static String company = "ParentCorp";   // static
        String        branch  = "Head Office";  // instance
        int           revenue = 1000000;
    }

    static class Child extends Parent {
        static String company = "ChildCorp";     // shadows Parent.company
        String        branch  = "Branch Office"; // shadows Parent.branch

        void showVariables() {
            System.out.println("=== Static Variables ===");
            System.out.println("company (child):  " + company);
            System.out.println("company (parent): " + super.company);
            // OR: Parent.company

            System.out.println("\n=== Instance Variables ===");
            System.out.println("branch (child):  " + branch);
            System.out.println("branch (parent): " + super.branch);

            System.out.println("\n=== Not shadowed ===");
            System.out.println("revenue = " + revenue);       // parent ka only
            System.out.println("revenue = " + super.revenue);  // same
        }
    }

    public static void main(String[] args) {
        Child c = new Child();
        c.showVariables();

        System.out.println("\n=== Key Rule ===");
        System.out.println("super.variable → parent ka variable");
        System.out.println("Only needed when child shadows parent's var");
        System.out.println("If child doesn't redefine → parent's accessible");
    }
}
Output
=== Static Variables === company (child): ChildCorp company (parent): ParentCorp === Instance Variables === branch (child): Branch Office branch (parent): Head Office === Not shadowed === revenue = 1000000 revenue = 1000000 === Key Rule === super.variable → parent ka variable Only needed when child shadows parent's var If child doesn't redefine → parent's accessible
Short Explain: Static variables bhi shadow ho sakti hain — super.company se parent ki static variable access ki. revenue child ne redefine nahi kiya toh super likhne ya na likhne se same result!
🟢

USE 2: super.method() — Parent Method Call 5 Programs

Method Overriding: Child class mein parent ka SAME method likhna = Overriding class Animal { void sound() { print("Generic sound"); } ← parent } class Dog extends Animal { void sound() { print("Woof"); } ← override! } Dog d = new Dog(); d.sound(); → "Woof" (child ka) — parent ka silently replaced! Agar parent ka bhi chahiye: void sound() { super.sound(); → "Generic sound" (parent ka explicitly) print("Woof"); → "Woof" (child ka) }
super.method() ka real use — EXTEND parent's behavior: Child ka method = Parent ka method + Extra stuff void draw() { super.draw(); ← pehle parent ka kaam karo // phir extra kaam karo drawBorder(); addShadow(); } Agar super.draw() nahi likhte → parent ka draw() REPLACED ho jaata hai super.draw() likhne se parent ka INCLUDED rehta hai!

SuperMethod1.java
public class SuperMethod1 {

    static class Animal {
        String name;

        Animal(String name) {
            this.name = name;
        }

        void eat() {
            System.out.println(name + " is eating food");
        }

        void sleep() {
            System.out.println(name + " is sleeping");
        }

        void describe() {
            System.out.println("I am " + name
                + ", an animal");
        }
    }

    static class Dog extends Animal {

        String breed;

        Dog(String name, String breed) {
            super(name);
            this.breed = breed;
        }

        // Override eat() - extend parent's behavior
        void eat() {
            super.eat();                        // parent ka kaam
            System.out.println(name             // extra kaam
                + " wags tail while eating!");
        }

        // Override describe() - completely replace
        void describe() {
            super.describe();                   // parent ka line
            System.out.println("Specifically, I am a "  // extra
                + breed + " dog!");
        }

        // sleep() NOT overridden → parent's version used
    }

    public static void main(String[] args) {

        Dog d = new Dog("Tommy", "Labrador");

        System.out.println("--- eat() [extended] ---");
        d.eat();

        System.out.println("\n--- describe() [extended] ---");
        d.describe();

        System.out.println("\n--- sleep() [not overridden] ---");
        d.sleep(); // parent's version directly!

        System.out.println("\n--- Parent animal ---");
        Animal a = new Animal("Lion");
        a.eat();      // parent's original
        a.describe(); // parent's original
    }
}
Output
--- eat() [extended] --- Tommy is eating food Tommy wags tail while eating! --- describe() [extended] --- I am Tommy, an animal Specifically, I am a Labrador dog! --- sleep() [not overridden] --- Tommy is sleeping --- Parent animal --- Lion is eating food I am Lion, an animal
Short Explain: eat() mein super.eat() se parent ka kaam pehle hua, phir child ka extra kaam. sleep() override nahi kiya — directly parent ka chala. super.method() = "parent ka bhi karo + apna bhi karo"!

SuperMethod2.java
public class SuperMethod2 {

    // Salary calculation chain with super
    static class Employee {
        String name;
        double basicSalary;

        Employee(String name, double basic) {
            this.name        = name;
            this.basicSalary = basic;
        }

        double calculateSalary() {
            double hra = basicSalary * 0.20;
            double da  = basicSalary * 0.10;
            System.out.println("  [Employee] Basic: "
                + basicSalary);
            System.out.println("  [Employee] HRA:   " + hra);
            System.out.println("  [Employee] DA:    " + da);
            return basicSalary + hra + da;
        }

        void printSlip() {
            System.out.println("=== " + name + " Salary Slip ===");
            double total = calculateSalary();
            System.out.println("  TOTAL: Rs." + total);
        }
    }

    static class Manager extends Employee {
        double bonus;

        Manager(String name, double basic, double bonus) {
            super(name, basic);
            this.bonus = bonus;
        }

        double calculateSalary() {
            double basePay = super.calculateSalary(); // Employee's calc
            System.out.println("  [Manager] Bonus: " + bonus);
            return basePay + bonus;
        }
    }

    static class Director extends Manager {
        double stockOptions;

        Director(String name, double basic,
                 double bonus, double stocks) {
            super(name, basic, bonus);
            this.stockOptions = stocks;
        }

        double calculateSalary() {
            double managerPay = super.calculateSalary(); // Manager's calc
            System.out.println("  [Director] Stocks: " + stockOptions);
            return managerPay + stockOptions;
        }
    }

    public static void main(String[] args) {

        Employee emp = new Employee("Amit", 40000);
        emp.printSlip();

        System.out.println();
        Manager mgr = new Manager("Rahul", 80000, 20000);
        mgr.printSlip();

        System.out.println();
        Director dir = new Director("Priya", 150000, 50000, 100000);
        dir.printSlip();
    }
}
Output
=== Amit Salary Slip === [Employee] Basic: 40000.0 [Employee] HRA: 8000.0 [Employee] DA: 4000.0 TOTAL: Rs.52000.0 === Rahul Salary Slip === [Employee] Basic: 80000.0 [Employee] HRA: 16000.0 [Employee] DA: 8000.0 [Manager] Bonus: 20000.0 TOTAL: Rs.124000.0 === Priya Salary Slip === [Employee] Basic: 150000.0 [Employee] HRA: 30000.0 [Employee] DA: 15000.0 [Manager] Bonus: 50000.0 [Director] Stocks: 100000.0 TOTAL: Rs.345000.0
Short Explain: Beautiful chain! Director.calculateSalary()super.calculateSalary() = Manager → jo phir super.calculateSalary() = Employee call karta hai. Har level apna add karta hai!

SuperMethod3.java
public class SuperMethod3 {

    // super.method() vs direct call - clear difference
    static class Shape {
        String color;

        Shape(String color) {
            this.color = color;
        }

        void draw() {
            System.out.println("Drawing shape with color: " + color);
        }

        void display() {
            System.out.println("Shape: color=" + color);
        }
    }

    static class Circle extends Shape {
        double radius;

        Circle(String color, double radius) {
            super(color);
            this.radius = radius;
        }

        // WITH super - extends parent
        void draw() {
            super.draw();  // parent ka draw bhi hoga
            System.out.println("Drawing circle with radius: "
                + radius);
        }

        // WITHOUT super - completely replaces parent
        void display() {
            // super.display() NAHI call kiya
            System.out.println("Circle: r=" + radius
                + " color=" + color);
        }
    }

    static class ColoredCircle extends Circle {
        String borderColor;

        ColoredCircle(String fill, String border,
                      double radius) {
            super(fill, radius);
            this.borderColor = border;
        }

        void draw() {
            super.draw();  // Circle's draw (which calls Shape's draw!)
            System.out.println("Adding border: " + borderColor);
        }
    }

    public static void main(String[] args) {

        System.out.println("=== Circle ===");
        Circle c = new Circle("Red", 5.0);
        c.draw();    // super.draw() included
        System.out.println();
        c.display(); // super.display() NOT included

        System.out.println("\n=== ColoredCircle ===");
        ColoredCircle cc = new ColoredCircle(
            "Blue", "Black", 7.0);
        cc.draw();   // 3-level chain!

        System.out.println("\n=== Chain Explained ===");
        System.out.println("cc.draw():");
        System.out.println("  → super.draw() = Circle.draw()");
        System.out.println("      → super.draw() = Shape.draw()");
        System.out.println("      → 'Drawing circle r=7.0'");
        System.out.println("  → 'Adding border: Black'");
    }
}
Output
=== Circle === Drawing shape with color: Red Drawing circle with radius: 5.0 Circle: r=5.0 color=Red === ColoredCircle === Drawing shape with color: Blue Drawing circle with radius: 7.0 Adding border: Black === Chain Explained === cc.draw(): → super.draw() = Circle.draw() → super.draw() = Shape.draw() → 'Drawing circle r=7.0' → 'Adding border: Black'
Short Explain: draw() mein super.draw() = parent included. display() mein super nahi = parent replaced. ColoredCircle.draw() ek 3-level chain banata hai — Shape → Circle → ColoredCircle!

SuperMethod4.java
public class SuperMethod4 {

    static class Vehicle {
        String brand;
        int    speed = 0;

        Vehicle(String brand) {
            this.brand = brand;
        }

        void start() {
            System.out.println("[Vehicle] " + brand + " engine ON");
        }

        void accelerate(int amount) {
            speed += amount;
            System.out.println("[Vehicle] Speed: " + speed + "kmph");
        }

        void stop() {
            speed = 0;
            System.out.println("[Vehicle] " + brand + " stopped");
        }

        void status() {
            System.out.println("[Vehicle] " + brand
                + " speed=" + speed);
        }
    }

    static class ElectricCar extends Vehicle {
        int battery = 100;

        ElectricCar(String brand) {
            super(brand);
        }

        void start() {
            super.start();              // parent ka start
            System.out.println("[EV] Battery: "
                + battery + "%");
        }

        void accelerate(int amount) {
            if (battery > 10) {
                super.accelerate(amount); // parent ka accelerate
                battery -= 2;
                System.out.println("[EV] Battery now: "
                    + battery + "%");
            } else {
                System.out.println("[EV] Low battery! Charge first!");
            }
        }

        void stop() {
            super.stop();               // parent ka stop
            battery += 5;               // regenerative braking!
            System.out.println("[EV] Regen charging: "
                + battery + "%");
        }

        void status() {
            super.status();             // parent ka status
            System.out.println("[EV] Battery: " + battery + "%");
        }
    }

    public static void main(String[] args) {

        ElectricCar tesla = new ElectricCar("Tesla");

        tesla.start();
        System.out.println();

        tesla.accelerate(60);
        tesla.accelerate(40);
        System.out.println();

        tesla.status();
        System.out.println();

        tesla.stop();
        System.out.println();

        tesla.status();
    }
}
Output
[Vehicle] Tesla engine ON [EV] Battery: 100% [Vehicle] Speed: 60kmph [EV] Battery now: 98% [Vehicle] Speed: 100kmph [EV] Battery now: 96% [Vehicle] Tesla speed=100 [EV] Battery: 96% [Vehicle] Tesla stopped [EV] Regen charging: 101% [Vehicle] Tesla speed=0 [EV] Battery: 101%
Short Explain: Har method mein super.method() se parent ka kaam hua, phir EV-specific kaam. stop() mein super.stop() se speed 0 hua, phir regenerative braking se battery charge — real EV logic!

SuperMethod5.java
public class SuperMethod5 {

    // toString() override with super - real world pattern
    static class Product {
        String name;
        double price;
        String category;

        Product(String name, double price, String category) {
            this.name     = name;
            this.price    = price;
            this.category = category;
        }

        String getInfo() {
            return "Product[" + name
                + ", Rs." + price
                + ", " + category + "]";
        }

        void validate() {
            System.out.println("[Product] Validating name: "
                + (name != null && !name.isEmpty()
                   ? "OK" : "FAIL"));
            System.out.println("[Product] Validating price: "
                + (price > 0 ? "OK" : "FAIL"));
        }
    }

    static class ElectronicProduct extends Product {
        String brand;
        int    warrantyYears;

        ElectronicProduct(String name, double price,
                          String brand, int warranty) {
            super(name, price, "Electronics");
            this.brand         = brand;
            this.warrantyYears = warranty;
        }

        String getInfo() {
            return super.getInfo()          // parent's info
                + " + Electronic[" + brand
                + ", " + warrantyYears + "yr warranty]";
        }

        void validate() {
            super.validate();               // parent validation
            System.out.println("[Electronic] Validating brand: "
                + (brand != null ? "OK" : "FAIL"));
            System.out.println("[Electronic] Validating warranty: "
                + (warrantyYears > 0 ? "OK" : "FAIL"));
        }
    }

    static class Laptop extends ElectronicProduct {
        int    ramGB;
        int    storageGB;
        String processor;

        Laptop(String name, double price, String brand,
               int ram, int storage, String cpu) {
            super(name, price, brand, 2);
            this.ramGB     = ram;
            this.storageGB = storage;
            this.processor = cpu;
        }

        String getInfo() {
            return super.getInfo()          // electronic's info
                + " + Laptop[" + processor
                + ", " + ramGB + "GB RAM"
                + ", " + storageGB + "GB]";
        }

        void validate() {
            super.validate();               // electronic validation
            System.out.println("[Laptop] Validating RAM: "
                + (ramGB >= 4 ? "OK" : "LOW"));
        }
    }

    public static void main(String[] args) {

        Laptop laptop = new Laptop(
            "ThinkPad X1", 95000, "Lenovo",
            16, 512, "Intel i7");

        System.out.println("=== Product Info Chain ===");
        System.out.println(laptop.getInfo());

        System.out.println("\n=== Validation Chain ===");
        laptop.validate();
    }
}
Output
=== Product Info Chain === Product[ThinkPad X1, Rs.95000.0, Electronics] + Electronic[Lenovo, 2yr warranty] + Laptop[Intel i7, 16GB RAM, 512GB] === Validation Chain === [Product] Validating name: OK [Product] Validating price: OK [Electronic] Validating brand: OK [Electronic] Validating warranty: OK [Laptop] Validating RAM: OK
Short Explain: getInfo() chain — Laptopsuper.getInfo() = Electronicsuper.getInfo() = Product. Har level apna part add karta hai. validate() bhi same 3-level chain!
🔴

USE 3: super() — Parent Constructor Call 5 Programs

super() = Parent class ka constructor call karo WHY zaroori hai: Jab child object banta hai, parent part bhi initialize hona chahiye! Parent part initialize karne ka kaam → Parent constructor ka! Compiler ka behavior: Developer ne super() nahi likha: Child() { // compiler yahan super() add karta hai automatically! // super(); ← invisible line! this.childVar = 10; } Iska matlab: Parent ka 0-arg constructor HAMESHA pehle chalega! (Developer likhe ya na likhe!)
super() ke 3 Scenarios: SCENARIO 1: Parent mein 0-arg constructor hai class Parent { Parent() { } ← 0-arg available } class Child extends Parent { Child() { // super() automatically added by compiler! } } SCENARIO 2: Parent mein ONLY parameterized constructor class Parent { Parent(int x) { } ← 0-arg NAHI hai! } class Child extends Parent { Child() { super(10); ← COMPULSORY! Manually likhna padega! // Without this → Compile ERROR! } } SCENARIO 3: Parent mein dono available class Child extends Parent { Child() { super(); ← explicitly 0-arg // OR super(10); ← explicitly parameterized } }

SuperConstructor1.java
public class SuperConstructor1 {

    static class Animal {
        String name;
        String type;

        // 0-arg constructor
        Animal() {
            this.name = "Unknown";
            this.type = "Animal";
            System.out.println("Animal() 0-arg: "
                + name + ", " + type);
        }

        // Parameterized constructor
        Animal(String name, String type) {
            this.name = name;
            this.type = type;
            System.out.println("Animal(name,type): "
                + name + ", " + type);
        }
    }

    static class Dog extends Animal {

        String breed;

        // Child 1: Uses compiler's auto super()
        Dog(String breed) {
            // Compiler adds: super(); automatically!
            this.breed = breed;
            System.out.println("Dog(breed): " + breed);
        }

        // Child 2: Explicitly calls 0-arg super()
        Dog() {
            super();    // explicit 0-arg
            this.breed = "Mixed";
            System.out.println("Dog(): Mixed");
        }

        // Child 3: Calls parameterized super()
        Dog(String name, String breed) {
            super(name, "Domestic Dog"); // param super!
            this.breed = breed;
            System.out.println("Dog(name,breed): " + breed);
        }
    }

    public static void main(String[] args) {

        System.out.println("=== Case 1: Auto super() ===");
        Dog d1 = new Dog("Labrador");

        System.out.println("\n=== Case 2: Explicit super() ===");
        Dog d2 = new Dog();

        System.out.println("\n=== Case 3: Param super() ===");
        Dog d3 = new Dog("Tommy", "Golden Retriever");

        System.out.println("\n=== Values ===");
        System.out.println("d1: " + d1.name
            + " | " + d1.type + " | " + d1.breed);
        System.out.println("d2: " + d2.name
            + " | " + d2.type + " | " + d2.breed);
        System.out.println("d3: " + d3.name
            + " | " + d3.type + " | " + d3.breed);
    }
}
Output
=== Case 1: Auto super() === Animal() 0-arg: Unknown, Animal Dog(breed): Labrador === Case 2: Explicit super() === Animal() 0-arg: Unknown, Animal Dog(): Mixed === Case 3: Param super() === Animal(name,type): Tommy, Domestic Dog Dog(name,breed): Golden Retriever === Values === d1: Unknown | Animal | Labrador d2: Unknown | Animal | Mixed d3: Tommy | Domestic Dog | Golden Retriever
Short Explain: Case 1 mein developer ne super() nahi likha — compiler ne automatically add kiya, Animal() 0-arg chala. Case 3 mein super(name, "Domestic Dog") se parameterized constructor chala — name "Tommy" set hua!

SuperConstructor2.java
public class SuperConstructor2 {

    // COMPULSORY super() scenario
    static class Vehicle {

        String brand;
        String model;
        int    year;

        // ONLY parameterized — NO 0-arg constructor!
        Vehicle(String brand, String model, int year) {
            this.brand = brand;
            this.model = model;
            this.year  = year;
            System.out.println("Vehicle: "
                + brand + " " + model + " " + year);
        }
    }

    static class Car extends Vehicle {

        int    doors;
        String color;

        Car(String brand, String model, int year,
            int doors, String color) {
            super(brand, model, year);  // ← COMPULSORY!
                                        // Without this: ERROR!
                                        // "no default constructor"
            this.doors = doors;
            this.color = color;
            System.out.println("Car: " + doors
                + " doors, " + color);
        }

        // Super with just 2 args - pick specific constructor
        Car(String brand, String model) {
            super(brand, model, 2024);  // default year 2024
            this.doors = 4;
            this.color = "White";
            System.out.println("Car (defaults): 4 doors, White");
        }
    }

    static class SportsCar extends Car {
        int     horsepower;
        boolean turbo;

        SportsCar(String brand, String model,
                  int hp, boolean turbo) {
            super(brand, model, 2024, 2, "Red"); // Car's constructor
            this.horsepower = hp;
            this.turbo      = turbo;
            System.out.println("SportsCar: "
                + hp + "hp, turbo=" + turbo);
        }
    }

    public static void main(String[] args) {

        System.out.println("--- Full spec Car ---");
        Car c1 = new Car("Honda", "City",
                         2023, 4, "Silver");

        System.out.println("\n--- Default Car ---");
        Car c2 = new Car("Toyota", "Corolla");

        System.out.println("\n--- Sports Car ---");
        SportsCar sc = new SportsCar(
            "Ferrari", "F40", 478, true);

        System.out.println("\n--- Values ---");
        System.out.println(c1.brand + " " + c1.model
            + " " + c1.year + " " + c1.color);
        System.out.println(sc.brand + " " + sc.model
            + " " + sc.horsepower + "hp");
    }
}
Output
--- Full spec Car --- Vehicle: Honda City 2023 Car: 4 doors, Silver --- Default Car --- Vehicle: Toyota Corolla 2024 Car (defaults): 4 doors, White --- Sports Car --- Vehicle: Ferrari F40 2024 Car: 2 doors, Red SportsCar: 478hp, turbo=true --- Values --- Honda City 2023 Silver Ferrari F40 478hp
Short Explain: Vehicle mein sirf parameterized constructor — Car mein super(brand, model, year) COMPULSORY. Bina super() ke Java default constructor dhundhta hai jo exist nahi karta — compile error!

SuperConstructor3.java
public class SuperConstructor3 {

    // super() MUST be FIRST statement - demonstration
    static class Base {
        int x;

        Base(int x) {
            this.x = x;
            System.out.println("Base constructor: x=" + x);
        }
    }

    static class Derived extends Base {

        int y;

        // ✅ CORRECT: super() first
        Derived(int x, int y) {
            super(x);           // FIRST LINE!
            this.y = y;         // after super - OK!
            System.out.println("Derived: y=" + y);
        }

        // ✅ CORRECT: this() → which internally calls super()
        Derived(int value) {
            this(value, value * 2); // this() is first
            System.out.println("Derived single-arg done");
        }

        // ❌ WRONG (commented out — would cause compile error):
        // Derived(int x, int y, int z) {
        //     int sum = x + y;   ← CANNOT put code before super()!
        //     super(sum);         ← ERROR! super must be FIRST!
        // }

        void show() {
            System.out.println("x=" + x + " y=" + y);
        }
    }

    static class MultiLevel extends Derived {
        int z;

        // super() chains: MultiLevel → Derived → Base
        MultiLevel(int x, int y, int z) {
            super(x, y);        // Derived(int,int)
            this.z = z;
            System.out.println("MultiLevel: z=" + z);
        }

        void showAll() {
            System.out.println("x=" + x + " y=" + y
                + " z=" + z);
        }
    }

    public static void main(String[] args) {

        System.out.println("=== Constructor Chain ===\n");

        System.out.println("--- Derived(5, 10) ---");
        Derived d1 = new Derived(5, 10);
        d1.show();

        System.out.println("\n--- Derived(7) [this() chain] ---");
        Derived d2 = new Derived(7);
        d2.show();

        System.out.println("\n--- MultiLevel(1, 2, 3) ---");
        MultiLevel ml = new MultiLevel(1, 2, 3);
        ml.showAll();

        System.out.println("\n=== RULE ===");
        System.out.println("super() MUST be FIRST statement!");
        System.out.println("this() also MUST be FIRST statement!");
        System.out.println("So this() and super() cannot BOTH be first!");
        System.out.println("Only ONE of them per constructor!");
    }
}
Output
=== Constructor Chain === --- Derived(5, 10) --- Base constructor: x=5 Derived: y=10 --- Derived(7) [this() chain] --- Base constructor: x=7 Derived: y=14 Derived single-arg done --- MultiLevel(1, 2, 3) --- Base constructor: x=1 Derived: y=2 MultiLevel: z=3 === RULE === super() MUST be FIRST statement! this() also MUST be FIRST statement! So this() and super() cannot BOTH be first! Only ONE of them per constructor!
Short Explain: super() HAMESHA first line — agar pehle kuch likh diya toh compile error. this() bhi first line hota hai — isliye dono ek saath ek constructor mein nahi ho sakte!

SuperConstructor4.java
public class SuperConstructor4 {

    // Real world: Form validation with super
    static class FormField {
        String  fieldName;
        String  value;
        boolean required;

        FormField(String fieldName, boolean required) {
            this.fieldName = fieldName;
            this.required  = required;
            System.out.println("FormField created: " + fieldName);
        }

        boolean validate() {
            if (required && (value == null || value.isEmpty())) {
                System.out.println("[" + fieldName
                    + "] REQUIRED field is empty!");
                return false;
            }
            return true;
        }

        void setValue(String value) {
            this.value = value;
        }
    }

    static class EmailField extends FormField {
        String domain;

        EmailField(String fieldName, String requiredDomain) {
            super(fieldName, true); // email is always required!
            this.domain = requiredDomain;
        }

        boolean validate() {
            boolean parentValid = super.validate(); // parent check
            if (!parentValid) return false;

            // Extra email validation
            if (!value.contains("@") || !value.contains(".")) {
                System.out.println("[" + fieldName
                    + "] Invalid email format!");
                return false;
            }
            if (!value.endsWith(domain)) {
                System.out.println("[" + fieldName
                    + "] Must end with " + domain);
                return false;
            }
            System.out.println("[" + fieldName + "] Email OK!");
            return true;
        }
    }

    static class PasswordField extends FormField {
        int minLength;

        PasswordField(String fieldName, int minLength) {
            super(fieldName, true); // password is required!
            this.minLength = minLength;
        }

        boolean validate() {
            boolean parentValid = super.validate();
            if (!parentValid) return false;

            if (value.length() < minLength) {
                System.out.println("[" + fieldName
                    + "] Minimum " + minLength + " chars needed!");
                return false;
            }
            System.out.println("[" + fieldName + "] Password OK!");
            return true;
        }
    }

    public static void main(String[] args) {

        System.out.println("=== Form Validation ===\n");

        EmailField    email = new EmailField(
            "email", "@company.com");
        PasswordField pass  = new PasswordField(
            "password", 8);

        System.out.println("\n--- Test 1: Invalid data ---");
        email.setValue("notanemail");
        pass.setValue("abc");
        email.validate();
        pass.validate();

        System.out.println("\n--- Test 2: Valid data ---");
        email.setValue("rahul@company.com");
        pass.setValue("SecurePass123");
        email.validate();
        pass.validate();
    }
}
Output
=== Form Validation === FormField created: email FormField created: password --- Test 1: Invalid data --- [email] Invalid email format! [password] Minimum 8 chars needed! --- Test 2: Valid data --- [email] Email OK! [password] Password OK!
Short Explain: super(fieldName, true) — parent constructor call kiya required=true ke saath. super.validate() se pehle empty check kiya, phir email/password specific checks. Real-world form validation pattern!

SuperConstructor5.java — All 3 Uses Together!
public class SuperConstructor5 {

    // Complete super() - all 3 uses together
    static class Person {
        String name;
        int    age;
        static int personCount = 0;

        static {
            System.out.println("[Person] Class loaded!");
        }

        Person(String name, int age) {
            this.name = name;
            this.age  = age;
            personCount++;
            System.out.println("[Person] Created: "
                + name + " #" + personCount);
        }

        void introduce() {
            System.out.println("Hi, I'm " + name
                + ", " + age + " yrs");
        }

        String getBasicInfo() {
            return name + "(" + age + ")";
        }
    }

    static class Student extends Person {
        String course;
        double gpa;
        static int studentCount = 0;

        static {
            System.out.println("[Student] Class loaded!");
        }

        Student(String name, int age,
                String course, double gpa) {
            super(name, age);       // USE 3: super() constructor
            this.course = course;
            this.gpa    = gpa;
            studentCount++;
            System.out.println("[Student] Created: "
                + course + " #" + studentCount);
        }

        // USE 2: super.method() - extend parent's method
        void introduce() {
            super.introduce();      // parent ka introduce
            System.out.println("I study " + course
                + ", GPA: " + gpa);
        }

        // USE 1: super.variable - if needed
        String getFullInfo() {
            return super.getBasicInfo()  // parent method
                + " | " + course
                + " | GPA:" + gpa;
        }
    }

    public static void main(String[] args) {

        System.out.println("=== super - All 3 Uses ===\n");

        Student s1 = new Student("Rahul", 20, "CS", 3.8);
        Student s2 = new Student("Priya", 22, "IT", 3.9);

        System.out.println("\n=== introduce() ===");
        s1.introduce();  // USE 2 inside
        System.out.println();
        s2.introduce();

        System.out.println("\n=== getFullInfo() ===");
        System.out.println(s1.getFullInfo());
        System.out.println(s2.getFullInfo());

        System.out.println("\n=== Counts ===");
        System.out.println("Total Persons:  " + Person.personCount);
        System.out.println("Total Students: " + Student.studentCount);
    }
}
Output
=== super - All 3 Uses === [Person] Class loaded! [Student] Class loaded! [Person] Created: Rahul #1 [Student] Created: CS #1 [Person] Created: Priya #2 [Student] Created: IT #2 === introduce() === Hi, I'm Rahul, 20 yrs I study CS, GPA: 3.8 Hi, I'm Priya, 22 yrs I study IT, GPA: 3.9 === getFullInfo() === Rahul(20) | CS | GPA:3.8 Priya(22) | IT | GPA:3.9 === Counts === Total Persons: 2 Total Students: 2
Short Explain: Ek program mein teeno super uses — super(name, age) constructor call, super.introduce() method call, super.getBasicInfo() method call. Static initializer blocks bhi dono classes mein — class loading order bhi dikhti hai!
📋

Complete Revision Summary

╔══════════════════════════════════════════════════════════╗ ║ super KEYWORD - COMPLETE REVISION ║ ╠═════════════════╦════════════════════════════════════════╣ ║ USE 1 ║ super.variable ║ ║ ║ Parent ka variable access karo ║ ║ ║ Jab child ne same naam se shadow kiya ║ ╠═════════════════╬════════════════════════════════════════╣ ║ USE 2 ║ super.method() ║ ║ ║ Parent ka method explicitly call karo ║ ║ ║ Override ke baad bhi parent run karo ║ ╠═════════════════╬════════════════════════════════════════╣ ║ USE 3 ║ super() / super(args) ║ ║ ║ Parent constructor call karo ║ ║ ║ HAMESHA FIRST LINE ║ ║ ║ Parent 0-arg nahi → COMPULSORY likhna ║ ╠═════════════════╬════════════════════════════════════════╣ ║ COMPILER RULE ║ super() nahi likha → compiler adds it ║ ║ ║ Parent ka 0-arg HAMESHA pehle chalta ║ ╠═════════════════╬════════════════════════════════════════╣ ║ RESTRICTIONS ║ super() sirf constructor mein ║ ║ ║ Static method mein NAHI ║ ║ ║ super() aur this() ek saath NAHI ║ ║ ║ super.super NAHI (one level only) ║ ╚═════════════════╩════════════════════════════════════════╝

⭐ Interview Questions — Exam Sheet

Q: super() kab COMPULSORY hai?
A: Jab parent mein sirf parameterized constructor ho (0-arg constructor nahi ho) Tab child mein super(args) MANUALLY likhna padega!
Q: super() nahi likha to kya hoga?
A: Compiler automatically super() add karta hai Parent ka 0-arg constructor call hoga 0-arg available nahi to → COMPILE ERROR!
Q: super.super kyu nahi?
A: Java mein super sirf ONE level up jaata hai Grandparent tak directly nahi ja sakte
Q: super() aur this() kya ek saath use kar sakte?
A: NAHI! Dono FIRST statement hote hain Ek constructor mein sirf ek ho sakta hai
Q: Static method mein super use ho sakta hai?
A: NAHI! super ke liye object chahiye Static method bina object ke run hoti hai
Q: Difference: super.method() vs method()?
A: method() → child ka version (overridden) super.method() → parent ka version explicitly

⚠️ Common Mistakes Table

MistakeWrong ❌Right ✅
super() not firstx=5; super(10);super(10); x=5;
super in staticstatic void m(){ super.x; }Not possible in static
super.supersuper.super.method()Not allowed in Java
Missing super()Parent has only param constructor, child doesn't callAlways call super(args)
this + super boththis(); super();Choose only ONE
Golden Rule: File name = Class name exactly. SuperVariable1.java for class SuperVariable1!