super KeywordComplete Deep Revision Guide — Hinglish mein samjho, clearly padho | 5 Programs per topic with explanation
super.variable — Parent Variable Access 5 Programspublic 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(); } }
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!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(); } }
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.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"); } }
super sirf EK level upar jaata hai — direct parent ka. Grandparent tak directly super.super se nahi ja sakte — Java mein allowed nahi!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(); } }
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!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"); } }
super.company se parent ki static variable access ki. revenue child ne redefine nahi kiya toh super likhne ya na likhne se same result!super.method() — Parent Method Call 5 Programspublic 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 } }
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"!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(); } }
Director.calculateSalary() → super.calculateSalary() = Manager → jo phir super.calculateSalary() = Employee call karta hai. Har level apna add karta hai!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'"); } }
draw() mein super.draw() = parent included. display() mein super nahi = parent replaced. ColoredCircle.draw() ek 3-level chain banata hai — Shape → Circle → ColoredCircle!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(); } }
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!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(); } }
getInfo() chain — Laptop → super.getInfo() = Electronic → super.getInfo() = Product. Har level apna part add karta hai. validate() bhi same 3-level chain!super() — Parent Constructor Call 5 Programspublic 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); } }
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!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"); } }
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!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!"); } }
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!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(); } }
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!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); } }
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!| Mistake | Wrong ❌ | Right ✅ |
|---|---|---|
| super() not first | x=5; super(10); | super(10); x=5; |
| super in static | static void m(){ super.x; } | Not possible in static |
| super.super | super.super.method() | Not allowed in Java |
| Missing super() | Parent has only param constructor, child doesn't call | Always call super(args) |
| this + super both | this(); super(); | Choose only ONE |
SuperVariable1.java for class SuperVariable1!