โ˜• JAVA COMPLETE GUIDE

Abstract Classes
Deep Revision Guide

Concept se leke real programs tak โ€” sab kuch samjho, online compiler pe run karo

Abstract Method Concrete Method 5 Programs Rules & Concepts Interview Q&A Hinglish Explain
๐Ÿ“–

Abstract Class โ€” Deep Concept

Java start karte ho toh yeh topic sabse important hai โ€” isko properly samjho

๐Ÿง  Abstract Class Kya Hoti Hai?

Abstract class ek aadhi-poori (partially implemented) class hoti hai. Isme kuch kaam ho chuka hota hai (concrete methods), aur kuch kaam baaki rehta hai jo child class karti hai (abstract methods).

Real Life Example: Socho ek "Vehicle" blueprint hai. Har vehicle mein fuel hota hai, engine hoti hai โ€” yeh common cheezein concrete mein hain. Lekin "chalane ka tarika" har vehicle ka alag hai โ€” Car, Bike, Plane sab alag chalti hain โ€” yeh abstract method hai!

ATM Example (topic mein diya tha): ATM ki screen pe sirf "Withdraw", "Transfer", "Balance" dikhta hai โ€” andar ka circuit, server connection, encryption sab hidden hai. Yahi abstraction hai!

๐Ÿ”ด Abstract Method

  • Sirf declaration hoti hai โ€” koi body nahi
  • Semicolon ; se khatam hota hai
  • abstract keyword lagta hai
  • Child class ko override karna COMPULSORY hai
  • Abstract class mein hi ho sakta hai
abstract void show(); // no body! just ;

๐ŸŸข Concrete Method

  • Normal method โ€” declaration + body dono
  • Curly braces { } ke saath
  • Child class override kar sakti hai (optional)
  • Kisi bhi class mein ho sakta hai
  • Abstract class mein bhi ho sakta hai
void show() { // has body!
  System.out.println("Hello");
}
๐Ÿง  Abstract Class โ€” Structure in Memory
abstract class Animal { // Concrete method โ€” implementation HAI void breathe() { System.out.println("breathing..."); } // Abstract method โ€” implementation NAHI, child karega abstract void sound(); // โ† sirf declaration, koi { } abstract void move(); // โ† child class MUST override } // Animal a = new Animal(); โ† โŒ COMPILE ERROR! Object nahi banta! // Sirf reference ban sakta hai: Animal a; // โ† โœ… Reference variable โ€” OK! class Dog extends Animal { void sound() { System.out.println("Woof!"); } // โ† MUST override void move() { System.out.println("runs"); } // โ† MUST override } Dog d = new Dog(); // โ† โœ… Dog ka object ban sakta hai!

๐Ÿ’ก Abstraction Kyu Use Karte Hain? (Real Reason)

1. Common structure define karo: Ek parent class mein sab child classes ka blueprint define karo โ€” "har Animal mein sound() aur move() hona CHAHIYE".

2. Forced implementation: Abstract method likho toh compiler FORCE karta hai child class ko implement karne ke liye โ€” bhoolna impossible!

3. Code reuse: Common concrete methods (jaise breathe()) parent mein ek baar likho โ€” saari child classes use karengi.

4. Polymorphism: Animal a = new Dog() โ€” ek reference se alag alag child objects handle karo.

5. Partial implementation: Jab pata ho ki kuch cheezein common hain aur kuch child-specific โ€” tab abstract class best choice hai!

โšก Abstract Class vs Interface โ€” Short Difference (aage aayega poori detail mein)

Abstract class mein concrete methods bhi ho sakti hain โ€” variables bhi rakh sakte hain โ€” constructors bhi hote hain. Interface mein (Java 7 tak) sirf abstract methods hoti thi. Abstract class use karo jab kuch shared code bhi rakhna ho.

๐Ÿ“‹

All Rules โ€” Ek Jagah

Ye sab rules yaad rakho โ€” exam/interview mein hamesha aate hain

Rule 1

abstract keyword se class declare karo: abstract class Animal { }

Rule 2 โ€” MOST IMPORTANT

Abstract class ka object NAHI banta! Sirf reference variable ban sakta hai.

Rule 3

Child class ko saare abstract methods override karne COMPULSORY hain โ€” warna child bhi abstract ban jaayegi.

Rule 4

Abstract class mein constructor ho sakta hai โ€” instance variables initialize karne ke liye.

Rule 5

0 abstract methods bhi allowed hain โ€” phir bhi class abstract ho sakti hai (object nahi banega).

Rule 6

abstract keyword sirf class aur method pe lagta hai โ€” variables pe NAHI lagta.

Rule 7

Multiple child classes ek abstract class ko extend kar sakti hain โ€” apna apna implementation de ke.

Rule 8

abstract aur final ek saath NAHI lag sakte โ€” abstract = override karo, final = override mat karo (contradiction!).

Rule 9

Abstract class reference variable se child object hold kar sakte ho โ€” polymorphism!

Cheez Abstract Class mein Normal Class mein
Object banana โŒ NAHI ban sakta โœ… Ban sakta hai
Abstract methods โœ… Haan โ€” allowed โŒ Nahi โ€” allowed nahi
Concrete methods โœ… Haan โ€” allowed โœ… Haan โ€” allowed
Constructor โœ… Ho sakta hai โœ… Ho sakta hai
Variables (instance/static) โœ… Haan โ€” allowed โœ… Haan โ€” allowed
Reference variable โœ… Ban sakta hai โœ… Ban sakta hai
Child class extend kar sakti hai โœ… Haan โœ… Haan
abstract + final same class โŒ Impossible โ€” contradiction! final alag use hoti hai
๐Ÿ’ป

Program 1 โ€” Basic Abstract Class

File name: AbstractBasic.java โ€” Sabse simple example se shuru karte hain

๐ŸŽฏ Is Program Mein Kya Seekhoge?

โ€ข Abstract class kaise declare karte hain
โ€ข Abstract method kaise likhte hain (sirf declaration, no body)
โ€ข Child class mein abstract method override karna
โ€ข Abstract class ka object nahi banta โ€” error dekhna
โ€ข Abstract class reference se child object hold karna (polymorphism)

PROGRAM 1 AbstractBasic.java
AbstractBasic.java Basic Abstract + Override
// FILE NAME: AbstractBasic.java
// CONCEPT: Abstract class basic - Animal example

abstract class Animal {

    String name;     // instance variable โ€” allowed in abstract class
    String color;

    // Constructor โ€” abstract class mein bhi constructor hota hai!
    Animal(String name, String color) {
        this.name  = name;
        this.color = color;
        System.out.println("Animal created: " + name);
    }

    // ABSTRACT METHODS โ€” sirf declaration, koi body nahi!
    // Child class ko ye sab override karne PADENGE
    abstract void sound();     // โ† no { } โ€” sirf ; se khatam
    abstract void move();      // โ† har animal alag move karta hai
    abstract String getType(); // โ† return type bhi ho sakta hai

    // CONCRETE METHOD โ€” body hai, sabke liye same kaam
    void breathe() {
        System.out.println(name + " is breathing...");
    }

    void displayInfo() {
        System.out.println("Name  : " + name);
        System.out.println("Color : " + color);
        System.out.println("Type  : " + getType()); // calls child version!
    }
}

// Child class 1 โ€” Dog
class Dog extends Animal {

    String breed;

    Dog(String name, String color, String breed) {
        super(name, color);   // parent constructor call karo
        this.breed = breed;
    }

    // Abstract methods override โ€” COMPULSORY!
    void sound() {
        System.out.println(name + " says: Woof! Woof!");
    }

    void move() {
        System.out.println(name + " runs on 4 legs");
    }

    String getType() { return "Dog (" + breed + ")"; }

    // Dog ka apna extra method
    void fetch() {
        System.out.println(name + " fetches the ball!");
    }
}

// Child class 2 โ€” Eagle
class Eagle extends Animal {

    double wingspan;

    Eagle(String name, String color, double ws) {
        super(name, color);
        this.wingspan = ws;
    }

    void sound() {
        System.out.println(name + " screams: Kreeee!");
    }

    void move() {
        System.out.println(name + " flies at high altitude");
    }

    String getType() { return "Eagle (wingspan: " + wingspan + "m)"; }
}

// Child class 3 โ€” Fish
class Fish extends Animal {

    String waterType;

    Fish(String name, String color, String wt) {
        super(name, color);
        this.waterType = wt;
    }

    void sound() {
        System.out.println(name + " makes bubbles...");
    }

    void move() {
        System.out.println(name + " swims in " + waterType + " water");
    }

    String getType() { return "Fish (" + waterType + ")"; }
}

public class AbstractBasic {
    public static void main(String[] args) {

        System.out.println("=== Abstract Class Demo ===\n");

        // Animal a = new Animal("X","Y"); โ† COMPILE ERROR! Object nahi banta!

        // Creating child objects
        Dog   dog   = new Dog("Tommy", "Brown", "Labrador");
        Eagle eagle = new Eagle("Sky", "Black", 2.5);
        Fish  fish  = new Fish("Nemo", "Orange", "Salt");

        System.out.println("\n--- Dog ---");
        dog.displayInfo();   // concrete method from Animal
        dog.sound();          // overridden abstract method
        dog.move();           // overridden abstract method
        dog.breathe();        // concrete method from Animal
        dog.fetch();          // Dog's own method

        System.out.println("\n--- Eagle ---");
        eagle.displayInfo();
        eagle.sound();
        eagle.move();
        eagle.breathe();

        System.out.println("\n--- Fish ---");
        fish.displayInfo();
        fish.sound();
        fish.move();

        System.out.println("\n--- Polymorphism (Abstract reference) ---");
        Animal[] animals = { dog, eagle, fish }; // Abstract reference!
        for (Animal a : animals) {
            a.sound();  // each calls its own version!
            a.move();
        }
    }
}
โšก Expected Output
Animal created: Tommy
Animal created: Sky
Animal created: Nemo

--- Dog ---
Name  : Tommy
Color : Brown
Type  : Dog (Labrador)
Tommy says: Woof! Woof!
Tommy runs on 4 legs
Tommy is breathing...
Tommy fetches the ball!

--- Eagle ---
Name  : Sky
Color : Black
Type  : Eagle (wingspan: 2.5m)
Sky screams: Kreeee!
Sky flies at high altitude
Sky is breathing...

--- Fish ---
Name  : Nemo
Color : Orange
Type  : Fish (Salt)
Nemo makes bubbles...
Nemo swims in Salt water

--- Polymorphism (Abstract reference) ---
Tommy says: Woof! Woof!
Tommy runs on 4 legs
Sky screams: Kreeee!
Sky flies at high altitude
Nemo makes bubbles...
Nemo swims in Salt water
๐Ÿ’ฌ Explain

Abstract class: Animal mein sound(), move(), getType() abstract hain โ€” sirf declaration hai, koi body nahi. breathe() aur displayInfo() concrete hain โ€” body hai, sabke liye same kaam.

Child classes: Dog, Eagle, Fish teeno ne saare abstract methods override kiye โ€” compulsory tha. Agar ek bhi miss karte toh compile error!

Polymorphism: Animal[] animals = { dog, eagle, fish } โ€” abstract reference se teen alag objects. Loop mein a.sound() โ€” har object apna version call karta hai. Yahi abstraction ki real power hai!

๐Ÿ’ป

Program 2 โ€” Shapes (Real Polymorphism)

File name: AbstractShapes.java โ€” Abstract class ka most classic example

๐ŸŽฏ Is Program Mein Kya Seekhoge?

โ€ข Abstract class se multiple shapes ka area/perimeter calculate karna
โ€ข Array of abstract references โ€” ek loop mein sab handle karna
โ€ข Static method abstract class mein kaise hoti hai
โ€ข Constructor chaining โ€” super() ka use
โ€ข Real-world polymorphism โ€” ek variable, multiple behavior

PROGRAM 2 AbstractShapes.java
AbstractShapes.java Polymorphism + Shapes
// FILE NAME: AbstractShapes.java
// CONCEPT: Abstract class โ€” Shapes area/perimeter

abstract class Shape {

    String color;
    String shapeName;

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

    // Abstract methods โ€” har shape ki apni calculation
    abstract double getArea();
    abstract double getPerimeter();

    // Concrete method โ€” sab shapes ke liye same display
    void display() {
        System.out.println("Shape     : " + shapeName);
        System.out.println("Color     : " + color);
        System.out.printf ("Area      : %.2f%n", getArea());       // calls child!
        System.out.printf ("Perimeter : %.2f%n", getPerimeter());  // calls child!
    }

    // Concrete static method โ€” abstract class mein allowed
    static void printLine() {
        System.out.println("-".repeat(30));
    }
}

class Circle extends Shape {

    double radius;

    Circle(String color, double radius) {
        super(color, "Circle");   // parent constructor
        this.radius = radius;
    }

    double getArea()      { return Math.PI * radius * radius; }
    double getPerimeter() { return 2 * Math.PI * radius; }
}

class Rectangle extends Shape {

    double length, width;

    Rectangle(String color, double l, double w) {
        super(color, "Rectangle");
        this.length = l;
        this.width  = w;
    }

    double getArea()      { return length * width; }
    double getPerimeter() { return 2 * (length + width); }
}

class Triangle extends Shape {

    double a, b, c;  // three sides

    Triangle(String color, double a, double b, double c) {
        super(color, "Triangle");
        this.a = a; this.b = b; this.c = c;
    }

    double getArea() {
        double s = (a + b + c) / 2;      // Heron's formula
        return Math.sqrt(s*(s-a)*(s-b)*(s-c));
    }

    double getPerimeter() { return a + b + c; }
}

class Square extends Shape {

    double side;

    Square(String color, double side) {
        super(color, "Square");
        this.side = side;
    }

    double getArea()      { return side * side; }
    double getPerimeter() { return 4 * side; }
}

public class AbstractShapes {

    // Total area calculate karo โ€” abstract reference parameter!
    static double totalArea(Shape[] shapes) {
        double total = 0;
        for (Shape s : shapes) total += s.getArea();
        return total;
    }

    public static void main(String[] args) {

        System.out.println("=== Shapes โ€” Abstract Class ===\n");

        // Shape ka object nahi banta: Shape s = new Shape(); โ† ERROR

        // Abstract class reference = child objects (POLYMORPHISM!)
        Shape[] shapes = {
            new Circle("Red",    7),
            new Rectangle("Blue", 10, 5),
            new Triangle("Green", 3, 4, 5),
            new Square("Yellow", 6)
        };

        for (Shape s : shapes) {
            Shape.printLine();
            s.display();  // each calls its own getArea() and getPerimeter()
        }

        Shape.printLine();
        System.out.printf("\nTotal Area of all shapes: %.2f%n",
            totalArea(shapes));

        System.out.println("\n--- Largest Shape ---");
        Shape largest = shapes[0];
        for (Shape s : shapes) {
            if (s.getArea() > largest.getArea()) largest = s;
        }
        System.out.println("Largest: " + largest.shapeName
            + " (area=" + String.format("%.2f", largest.getArea()) + ")");
    }
}
โšก Expected Output
==============================
Shape     : Circle
Color     : Red
Area      : 153.94
Perimeter : 43.98
------------------------------
Shape     : Rectangle
Color     : Blue
Area      : 50.00
Perimeter : 30.00
------------------------------
Shape     : Triangle
Color     : Green
Area      : 6.00
Perimeter : 12.00
------------------------------
Shape     : Square
Color     : Yellow
Area      : 36.00
Perimeter : 24.00
------------------------------

Total Area of all shapes: 245.94

--- Largest Shape ---
Largest: Circle (area=153.94)
๐Ÿ’ฌ Explain

Abstract Shape class mein getArea() aur getPerimeter() abstract hain โ€” formula har shape ka alag hai. display() concrete hai โ€” printing sab ke liye same, lekin andar getArea() call karta hai jo child version chalata hai.

Shape[] array โ€” ek array mein Circle, Rectangle, Triangle, Square sab rakh liye. for loop mein s.getArea() โ€” automatically sahi formula call hota hai. Yahi abstraction ki power hai โ€” ek interface, alag alag implementation!

๐Ÿ’ป

Program 3 โ€” Constructor in Abstract Class

File name: AbstractConstructor.java โ€” Constructor ka role samjho

๐ŸŽฏ Is Program Mein Kya Seekhoge?

โ€ข Abstract class mein constructor hota hai โ€” super() se call hota hai
โ€ข Constructor chain โ€” child โ†’ parent constructor
โ€ข Instance variables abstract class mein โ€” kaise initialize hote hain
โ€ข Abstract method with parameters
โ€ข Partial implementation โ€” kuch methods concrete, kuch abstract

PROGRAM 3 AbstractConstructor.java
AbstractConstructor.java Constructor + super() + Vehicle
// FILE NAME: AbstractConstructor.java
// CONCEPT: Constructor in Abstract class โ€” Vehicle example

abstract class Vehicle {

    // Instance variables โ€” abstract class mein hote hain
    String  brand;
    String  model;
    int     year;
    double  price;

    // CONSTRUCTOR โ€” abstract class mein hota hai!
    // Direct object nahi banta, but child super() se call karta hai
    Vehicle(String brand, String model, int year, double price) {
        this.brand = brand;
        this.model = model;
        this.year  = year;
        this.price = price;
        System.out.println("[Vehicle Constructor] " + brand + " " + model + " initialized");
    }

    // ABSTRACT METHODS โ€” child must implement
    abstract void fuelType();
    abstract int  seatingCapacity();
    abstract void specialFeature();

    // CONCRETE METHODS โ€” common for all vehicles
    void startEngine() {
        System.out.println(brand + " " + model + ": Engine Started! Vroom!");
    }

    void stopEngine() {
        System.out.println(brand + " " + model + ": Engine Stopped.");
    }

    void displayDetails() {
        System.out.println("Brand    : " + brand);
        System.out.println("Model    : " + model);
        System.out.println("Year     : " + year);
        System.out.printf ("Price    : Rs.%.0f%n", price);
        System.out.println("Seats    : " + seatingCapacity()); // calls child!
        fuelType();                                          // calls child!
        specialFeature();                                    // calls child!
    }
}

class Car extends Vehicle {

    int     doors;
    boolean hasAC;

    Car(String brand, String model, int year,
        double price, int doors, boolean ac) {
        super(brand, model, year, price);  // Vehicle constructor call!
        this.doors = doors;
        this.hasAC  = ac;
    }

    void  fuelType()        { System.out.println("Fuel     : Petrol/Diesel"); }
    int   seatingCapacity() { return 5; }
    void  specialFeature() {
        System.out.println("Feature  : " + doors + "-door, AC=" + hasAC);
    }
}

class ElectricCar extends Vehicle {

    int    batteryCapacity; // kWh
    int    range;           // km per charge

    ElectricCar(String brand, String model, int year,
                double price, int bat, int range) {
        super(brand, model, year, price);
        this.batteryCapacity = bat;
        this.range           = range;
    }

    void  fuelType()        { System.out.println("Fuel     : Electric (Battery)"); }
    int   seatingCapacity() { return 5; }
    void  specialFeature() {
        System.out.println("Feature  : Battery=" + batteryCapacity
            + "kWh, Range=" + range + "km");
    }

    void charge() {
        System.out.println(brand + " " + model + ": Charging... 0โ†’100% โšก");
    }
}

class Bus extends Vehicle {

    int     seats;
    String  route;

    Bus(String brand, String model, int year,
        double price, int seats, String route) {
        super(brand, model, year, price);
        this.seats = seats;
        this.route = route;
    }

    void  fuelType()        { System.out.println("Fuel     : Diesel/CNG"); }
    int   seatingCapacity() { return seats; }
    void  specialFeature() {
        System.out.println("Feature  : Route - " + route);
    }
}

public class AbstractConstructor {
    public static void main(String[] args) {

        System.out.println("=== Vehicle Abstract Class ===\n");
        System.out.println("--- Creating objects (constructors called) ---");

        Car         car1 = new Car("Maruti", "Swift", 2023, 800000, 4, true);
        ElectricCar ev   = new ElectricCar("Tata", "Nexon EV", 2024, 1500000, 40, 400);
        Bus         bus  = new Bus("Volvo", "B9R", 2022, 5000000, 45, "Delhi-Mumbai");

        System.out.println("\n--- Car Details ---");
        car1.displayDetails();
        car1.startEngine();

        System.out.println("\n--- Electric Car Details ---");
        ev.displayDetails();
        ev.charge();        // ElectricCar ka extra method

        System.out.println("\n--- Bus Details ---");
        bus.displayDetails();
        bus.startEngine();
        bus.stopEngine();

        System.out.println("\n--- Total Fleet Seating ---");
        Vehicle[] fleet = { car1, ev, bus };
        int totalSeats = 0;
        for (Vehicle v : fleet) totalSeats += v.seatingCapacity();
        System.out.println("Total Seats: " + totalSeats);
    }
}
โšก Expected Output
[Vehicle Constructor] Maruti Swift initialized
[Vehicle Constructor] Tata Nexon EV initialized
[Vehicle Constructor] Volvo B9R initialized

--- Car Details ---
Brand    : Maruti
Model    : Swift
Year     : 2023
Price    : Rs.800000
Seats    : 5
Fuel     : Petrol/Diesel
Feature  : 4-door, AC=true
Maruti Swift: Engine Started! Vroom!

--- Electric Car Details ---
Brand    : Tata
Model    : Nexon EV
Year     : 2024
Price    : Rs.1500000
Seats    : 5
Fuel     : Electric (Battery)
Feature  : Battery=40kWh, Range=400km
Tata Nexon EV: Charging... 0โ†’100% โšก

--- Bus Details ---
Brand    : Volvo
Model    : B9R
Year     : 2022
Price    : Rs.5000000
Seats    : 45
Fuel     : Diesel/CNG
Feature  : Route - Delhi-Mumbai
Volvo B9R: Engine Started! Vroom!
Volvo B9R: Engine Stopped.

--- Total Fleet Seating ---
Total Seats: 55
๐Ÿ’ฌ Explain

Constructor chain: new Car(...) call hota hai โ†’ Car constructor โ†’ super(brand, model, year, price) โ†’ Vehicle constructor pehle chalta hai! Tab Car constructor baaki code chalta hai.

Abstract class mein constructor kyu? Variables like brand, model, year, price sab vehicles mein common hain โ€” inhe ek jagah initialize karo. Child classes sirf apne extra variables initialize karein.

displayDetails() mein seatingCapacity(), fuelType(), specialFeature() call hote hain โ€” runtime pe child ka version chalta hai. Vehicle constructor chala โ†’ "Vehicle Constructor" print hua โ€” proof ki abstract class ka constructor kaam karta hai!

๐Ÿ’ป

Program 4 โ€” Abstract + Interface Together

File name: AbstractWithInterface.java โ€” Dono concepts ek saath

๐ŸŽฏ Is Program Mein Kya Seekhoge?

โ€ข Abstract class aur interface dono use karna
โ€ข Abstract class interface implement kar sakti hai
โ€ข Template Method Pattern โ€” algorithm structure abstract mein, steps child mein
โ€ข Multiple levels of abstraction
โ€ข Real project jesi architecture

PROGRAM 4 AbstractWithInterface.java
AbstractWithInterface.java Abstract + Interface + Template Pattern
// FILE NAME: AbstractWithInterface.java
// CONCEPT: Abstract class + Interface โ€” Employee system

// Interface โ€” pure contract (kya karna chahiye)
interface Workable {
    void work();
    void takeBreak();
}

// Interface โ€” payment contract
interface Payable {
    double calculateSalary();
    void   printPaySlip();
}

// Abstract class โ€” interface implement karta hai
// + apni abstract methods bhi add karta hai
abstract class Employee implements Workable, Payable {

    String name;
    String empId;
    String department;
    double baseSalary;

    Employee(String name, String empId,
              String dept, double base) {
        this.name       = name;
        this.empId      = empId;
        this.department = dept;
        this.baseSalary = base;
    }

    // Abstract methods โ€” child class apna implement karega
    abstract String getRole();
    abstract double getBonus();

    // Concrete from Workable interface โ€” default implementation
    public void takeBreak() {
        System.out.println(name + " is on a break.");
    }

    // Concrete โ€” salary print (common for all)
    public void printPaySlip() {
        System.out.println("--- Pay Slip ---");
        System.out.println("Name      : " + name);
        System.out.println("ID        : " + empId);
        System.out.println("Dept      : " + department);
        System.out.println("Role      : " + getRole());        // calls child
        System.out.printf ("Base      : Rs.%.0f%n", baseSalary);
        System.out.printf ("Bonus     : Rs.%.0f%n", getBonus()); // calls child
        System.out.printf ("Total     : Rs.%.0f%n", calculateSalary()); // calls child
    }
}

// Concrete class 1
class Developer extends Employee {

    String language;
    int    experience;

    Developer(String name, String id, double base,
               String lang, int exp) {
        super(name, id, "Engineering", base);
        this.language   = lang;
        this.experience = exp;
    }

    public void   work()   { System.out.println(name + " is coding in " + language); }
    public String getRole()  { return "Senior Developer (" + language + ")"; }
    public double getBonus() { return baseSalary * 0.25; }  // 25%

    public double calculateSalary() {
        return baseSalary + getBonus() + (experience * 1000);
    }

    void deployCode() {
        System.out.println(name + " deployed code to production!");
    }
}

// Concrete class 2
class Manager extends Employee {

    int    teamSize;
    String projectName;

    Manager(String name, String id, double base,
             int team, String proj) {
        super(name, id, "Management", base);
        this.teamSize    = team;
        this.projectName = proj;
    }

    public void   work()   { System.out.println(name + " is managing project: " + projectName); }
    public String getRole()  { return "Project Manager (" + teamSize + " team)"; }
    public double getBonus() { return baseSalary * 0.40; }  // 40%

    public double calculateSalary() {
        return baseSalary + getBonus() + (teamSize * 500);
    }
}

// Concrete class 3 โ€” Intern
class Intern extends Employee {

    int durationMonths;

    Intern(String name, String id,
            double stipend, int months) {
        super(name, id, "Internship", stipend);
        this.durationMonths = months;
    }

    public void   work()   { System.out.println(name + " is learning and assisting"); }
    public String getRole()  { return "Intern (" + durationMonths + " months)"; }
    public double getBonus() { return 0; }  // no bonus for intern
    public double calculateSalary() { return baseSalary; }
}

public class AbstractWithInterface {

    // Accept any Employee โ€” Workable โ€” Payable
    static void processEmployee(Employee e) {
        e.work();
        e.printPaySlip();
        System.out.println();
    }

    public static void main(String[] args) {

        System.out.println("=== Company Payroll System ===\n");

        Developer dev  = new Developer("Rahul", "D001", 80000, "Java", 3);
        Manager   mgr  = new Manager("Priya",  "M001", 120000, 8, "ERP System");
        Intern    intn = new Intern("Ankit",  "I001", 15000, 6);

        processEmployee(dev);
        processEmployee(mgr);
        processEmployee(intn);

        System.out.println("--- Total Payroll ---");
        Employee[] team = { dev, mgr, intn };
        double totalPayroll = 0;
        for (Employee e : team) totalPayroll += e.calculateSalary();
        System.out.printf("Total: Rs.%.0f%n", totalPayroll);

        System.out.println("\n--- Interface reference ---");
        // Abstract class implements interface โ€” so interface ref also works!
        Workable[] workers = { dev, mgr, intn };
        for (Workable w : workers) w.work();
    }
}
โšก Expected Output
Rahul is coding in Java
--- Pay Slip ---
Name      : Rahul
ID        : D001
Dept      : Engineering
Role      : Senior Developer (Java)
Base      : Rs.80000
Bonus     : Rs.20000
Total     : Rs.103000

Priya is managing project: ERP System
--- Pay Slip ---
Name      : Priya
ID        : M001
Dept      : Management
Role      : Project Manager (8 team)
Base      : Rs.120000
Bonus     : Rs.48000
Total     : Rs.172000

Ankit is learning and assisting
--- Pay Slip ---
Name      : Ankit
ID        : I001
Dept      : Internship
Role      : Intern (6 months)
Base      : Rs.15000
Bonus     : Rs.0
Total     : Rs.15000

--- Total Payroll ---
Total: Rs.290000

--- Interface reference ---
Rahul is coding in Java
Priya is managing project: ERP System
Ankit is learning and assisting
๐Ÿ’ฌ Explain

Abstract class + Interface: Employee abstract class ne Workable aur Payable dono interfaces implement kiye โ€” lekin work() aur calculateSalary() abstract chhod diye (child karega). takeBreak() aur printPaySlip() concrete diye.

Key insight: Workable[] workers = { dev, mgr, intn } โ€” interface reference bhi kaam karta hai kyunki Employee Workable implement karta hai. Ek hi system mein Developer, Manager, Intern sab alag salary calculate karte hain โ€” yahi abstraction ka real power!

๐Ÿ’ป

Program 5 โ€” Bank System (Complete Real-World)

File name: AbstractBankSystem.java โ€” Poora end-to-end example

๐ŸŽฏ Is Program Mein Kya Seekhoge?

โ€ข Sab concepts ek jagah โ€” abstract class, constructor, concrete + abstract methods
โ€ข Real-world bank account system
โ€ข Multiple types of accounts โ€” ek abstract parent
โ€ข Abstract class reference array โ€” polymorphism
โ€ข Template pattern โ€” abstract structure, child implementation

PROGRAM 5 AbstractBankSystem.java
AbstractBankSystem.java Complete Bank System โ€” All Concepts
// FILE NAME: AbstractBankSystem.java
// CONCEPT: Complete abstract class โ€” Bank Account System

abstract class BankAccount {

    // Instance variables
    protected String accountNo;
    protected String holderName;
    protected double balance;
    protected  String bankName;

    // Static variable โ€” total accounts
    static int totalAccounts = 0;

    // CONSTRUCTOR โ€” initialize common data
    BankAccount(String accNo, String holder,
                double initialBalance, String bank) {
        this.accountNo   = accNo;
        this.holderName  = holder;
        this.balance     = initialBalance;
        this.bankName    = bank;
        totalAccounts++;
        System.out.println("[BANK] Account created: " + accNo + " for " + holder);
    }

    // ABSTRACT METHODS โ€” each account type handles differently
    abstract void   withdraw(double amount);
    abstract void   applyMonthlyCharge();
    abstract String getAccountType();
    abstract double getInterestRate();

    // CONCRETE METHODS โ€” same for all account types
    void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
            System.out.printf("[DEPOSIT] +Rs.%.0f | Balance: Rs.%.0f%n", amount, balance);
        } else {
            System.out.println("[ERROR] Invalid deposit amount!");
        }
    }

    void checkBalance() {
        System.out.printf("[BALANCE] %s: Rs.%.0f%n", holderName, balance);
    }

    void printStatement() {
        System.out.println("==============================");
        System.out.println("Bank      : " + bankName);
        System.out.println("Account   : " + accountNo);
        System.out.println("Holder    : " + holderName);
        System.out.println("Type      : " + getAccountType()); // abstract!
        System.out.printf ("Balance   : Rs.%.2f%n", balance);
        System.out.printf ("Interest  : %.1f%% p.a.%n", getInterestRate()); // abstract!
        System.out.println("==============================");
    }

    double getBalance() { return balance; }
}

// Savings Account โ€” min balance required
class SavingsAccount extends BankAccount {

    static final double MIN_BALANCE = 1000;
    double interestRate;

    SavingsAccount(String accNo, String holder,
                    double balance, String bank, double rate) {
        super(accNo, holder, balance, bank);
        this.interestRate = rate;
    }

    void withdraw(double amount) {
        if (balance - amount < MIN_BALANCE) {
            System.out.printf("[ERROR] Min balance Rs.%.0f required! Withdraw failed.%n", MIN_BALANCE);
        } else {
            balance -= amount;
            System.out.printf("[WITHDRAW] -Rs.%.0f | Balance: Rs.%.0f%n", amount, balance);
        }
    }

    void applyMonthlyCharge() {
        double interest = balance * interestRate / 12 / 100;
        balance += interest;
        System.out.printf("[INTEREST @%.1f%%] +Rs.%.2f | New Balance: Rs.%.2f%n",
            interestRate, interest, balance);
    }

    String getAccountType() { return "Savings Account"; }
    double getInterestRate() { return interestRate; }
}

// Current Account โ€” overdraft allowed
class CurrentAccount extends BankAccount {

    double overdraftLimit;
    double maintenanceFee;

    CurrentAccount(String accNo, String holder,
                    double balance, String bank,
                    double overdraft, double fee) {
        super(accNo, holder, balance, bank);
        this.overdraftLimit = overdraft;
        this.maintenanceFee = fee;
    }

    void withdraw(double amount) {
        if (balance - amount < -overdraftLimit) {
            System.out.println("[ERROR] Overdraft limit exceeded!");
        } else {
            balance -= amount;
            System.out.printf("[WITHDRAW] -Rs.%.0f | Balance: Rs.%.0f%n", amount, balance);
            if (balance < 0)
                System.out.printf("  (Overdraft used: Rs.%.0f)%n", -balance);
        }
    }

    void applyMonthlyCharge() {
        balance -= maintenanceFee;
        System.out.printf("[MAINTENANCE] -Rs.%.0f | Balance: Rs.%.2f%n",
            maintenanceFee, balance);
    }

    String getAccountType() { return "Current Account"; }
    double getInterestRate() { return 0.0; } // No interest on current
}

// Fixed Deposit โ€” cannot withdraw early
class FixedDeposit extends BankAccount {

    int    tenureMonths;
    double fdRate;

    FixedDeposit(String accNo, String holder,
                 double principal, String bank,
                 int months, double rate) {
        super(accNo, holder, principal, bank);
        this.tenureMonths = months;
        this.fdRate       = rate;
    }

    void withdraw(double amount) {
        System.out.println("[ERROR] FD cannot be withdrawn before maturity!");
    }

    void applyMonthlyCharge() {
        double interest = balance * fdRate / 12 / 100;
        balance += interest;
        System.out.printf("[FD INTEREST @%.1f%%] +Rs.%.2f | Total: Rs.%.2f%n",
            fdRate, interest, balance);
    }

    void mature() {
        System.out.printf("[MATURED] FD %s matured! Amount: Rs.%.2f%n",
            accountNo, balance);
    }

    String getAccountType() { return "Fixed Deposit (" + tenureMonths + " months)"; }
    double getInterestRate() { return fdRate; }
}

public class AbstractBankSystem {

    public static void main(String[] args) {

        System.out.println("=== Abstract Bank System ===\n");

        // Creating accounts
        SavingsAccount savings = new SavingsAccount(
            "SB001", "Rahul", 50000, "SBI", 6.5);

        CurrentAccount current = new CurrentAccount(
            "CA001", "Priya Enterprises", 100000, "HDFC", 20000, 500);

        FixedDeposit fd = new FixedDeposit(
            "FD001", "Suresh", 200000, "ICICI", 12, 7.5);

        System.out.println("\n=== Statements ===");
        savings.printStatement();
        current.printStatement();
        fd.printStatement();

        System.out.println("\n=== Transactions ===");
        savings.deposit(10000);
        savings.withdraw(5000);
        savings.withdraw(55000);  // will fail โ€” min balance

        current.deposit(5000);
        current.withdraw(110000); // uses overdraft

        fd.withdraw(10000);       // will fail โ€” FD
        fd.deposit(10000);        // allowed

        System.out.println("\n=== Monthly Processing ===");
        BankAccount[] allAccounts = { savings, current, fd };
        for (BankAccount acc : allAccounts) {
            System.out.print("Processing " + acc.holderName + ": ");
            acc.applyMonthlyCharge(); // each account type handles differently!
        }

        System.out.println("\n=== Final Balances ===");
        double total = 0;
        for (BankAccount acc : allAccounts) {
            acc.checkBalance();
            total += acc.getBalance();
        }
        System.out.printf("Total Bank Assets: Rs.%.2f%n", total);
        System.out.println("Total Accounts Opened: " + BankAccount.totalAccounts);
    }
}
โšก Expected Output
[BANK] Account created: SB001 for Rahul
[BANK] Account created: CA001 for Priya Enterprises
[BANK] Account created: FD001 for Suresh

=== Statements ===
==============================
Bank      : SBI
Account   : SB001
Holder    : Rahul
Type      : Savings Account
Balance   : Rs.50000.00
Interest  : 6.5% p.a.
==============================
==============================
Bank      : HDFC
Account   : CA001
Holder    : Priya Enterprises
Type      : Current Account
Balance   : Rs.100000.00
Interest  : 0.0% p.a.
==============================
==============================
Bank      : ICICI
Account   : FD001
Holder    : Suresh
Type      : Fixed Deposit (12 months)
Balance   : Rs.200000.00
Interest  : 7.5% p.a.
==============================

=== Transactions ===
[DEPOSIT] +Rs.10000 | Balance: Rs.60000
[WITHDRAW] -Rs.5000 | Balance: Rs.55000
[ERROR] Min balance Rs.1000 required! Withdraw failed.
[DEPOSIT] +Rs.5000 | Balance: Rs.105000
[WITHDRAW] -Rs.110000 | Balance: Rs.-5000
  (Overdraft used: Rs.5000)
[ERROR] FD cannot be withdrawn before maturity!
[DEPOSIT] +Rs.10000 | Balance: Rs.210000

=== Monthly Processing ===
Processing Rahul: [INTEREST @6.5%] +Rs.297.92 | New Balance: Rs.55297.92
Processing Priya Enterprises: [MAINTENANCE] -Rs.500 | Balance: Rs.-5500.00
Processing Suresh: [FD INTEREST @7.5%] +Rs.1312.50 | Total: Rs.211312.50

=== Final Balances ===
[BALANCE] Rahul: Rs.55298
[BALANCE] Priya Enterprises: Rs.-5500
[BALANCE] Suresh: Rs.211313
Total Bank Assets: Rs.261110.42
Total Accounts Opened: 3
๐Ÿ’ฌ Explain

BankAccount abstract class mein withdraw() aur applyMonthlyCharge() abstract hain โ€” kyunki har account type alag behave karta hai. Savings mein min balance check, Current mein overdraft allowed, FD mein withdrawal forbidden!

BankAccount[] allAccounts โ€” ek array mein teeno types. Monthly processing mein acc.applyMonthlyCharge() โ€” Savings ko interest mila, Current se maintenance fee gaya, FD ko FD interest mila. Ek method call, teen alag behaviors โ€” yahi abstraction + polymorphism ka combination hai!

Constructor: Har account object bana โ†’ "Account created" print hua โ€” proof ki abstract class constructor chalta hai via super().

โญ

Interview / Exam Questions

Ye sab questions zaroor aate hain โ€” ache se padho

Q1 ยท Abstract class ka object kyu nahi ban sakta?
Kyunki abstract class partially implemented hoti hai โ€” iske kuch methods (abstract methods) ka implementation hi nahi hai. Agar object ban jaata toh un methods ko call karte waqt kya chalta? Isliye Java compile-time pe hi rok deta hai. Sirf completely implemented class (concrete class) ka object ban sakta hai.
Q2 ยท Kya abstract class mein 0 abstract methods ho sakte hain?
Haan! Abstract class mein zero abstract methods bhi allowed hain โ€” sirf abstract keyword lagao class pe. Tab bhi object nahi banega. Ye useful hai jab tum chahte ho ki class extend ho sake but directly instantiate na ho sake.
Q3 ยท Abstract class aur Interface mein kya difference hai?
Abstract Class: Concrete methods bhi ho sakti hain ยท Variables (instance/static) ho sakte hain ยท Constructor hota hai ยท Single inheritance (ek hi extend kar sakte hain)

Interface (Java 7 tak): Sirf abstract methods ยท Variables automatically public static final ยท Constructor nahi ยท Multiple interfaces implement kar sakte hain

Use karo: Shared code bhi chahiye โ†’ Abstract class. Sirf contract chahiye โ†’ Interface.
Q4 ยท Abstract class mein constructor ka kya kaam hai?
Abstract class ka object seedha nahi banta, lekin jab child class ka object banta hai toh super() se parent (abstract) constructor call hota hai. Yeh constructor instance variables initialize karta hai jo saari child classes share karte hain. Isliye abstract class mein constructor hona bahut useful hai.
Q5 ยท Agar child class saare abstract methods override nahi kare toh kya hoga?
Child class ko bhi abstract declare karna padega โ€” warna compile error! Jab tak koi class saare abstract methods implement nahi karta, woh bhi abstract ban jaati hai. Sirf concrete class (jisme saare methods implemented hain) ka object ban sakta hai.
Q6 ยท Abstract aur final ek saath kyu nahi lag sakte?
Direct contradiction hai! abstract ka matlab โ€” "is method ko override karo" (compulsory). final ka matlab โ€” "is method ko override mat karo" (forbidden). Dono ek saath impossible โ€” isliye Java compile error deta hai.
Q7 ยท Abstract class reference se kya kya kar sakte hain?
Animal a; โ€” reference variable declare kar sakte hain โœ…
Animal a = new Dog(); โ€” child object hold kar sakte hain โœ…
Animal a = new Animal(); โ€” object nahi bana sakte โŒ

Reference se sirf parent class ke methods accessible hote hain. Overridden methods child version chalate hain (polymorphism).
Q8 ยท Abstract keyword variables pe kyu nahi lagta?
Abstract ka concept methods pe apply hota hai โ€” "method ka implementation baad mein hoga". Variable pe koi "implementation" nahi hoti โ€” variable sirf value store karta hai. Isliye abstract int x; โ€” invalid. Variables pe final, static, private lag sakte hain lekin abstract nahi.

โšก Quick Revision โ€” Sab Kuch 30 Seconds Mein

Abstract class = partially implemented class ยท Object nahi banta ยท Sirf reference ban sakta hai
Abstract method = sirf declaration (abstract void show();) ยท No body ยท Child must override
Concrete method = normal method with body ยท Optional override
Constructor = abstract class mein bhi hota hai ยท super() se call hota hai
Polymorphism = Animal a = new Dog() ยท a.sound() โ†’ Dog ka version chalta hai
Rule = abstract + final = impossible ยท abstract sirf class aur method pe

โ†‘