Java OOP
Abstraction
Complete lesson for Abstraction using LEARNCODEGURU’s 6-level learning model — from basics to advanced practice, with Java OOP and Collections where relevant.
Basics — Abstraction
Section: Java OOP. Show what an object does, hide how it does it — abstract classes, abstract methods, interfaces, real-life examples, and design patterns.
What is abstraction?
- Abstraction means showing only the essential features of an object and hiding the implementation details.
- It answers "what does it do?" and hides "how does it do it?".
- Real life: you drive a car with the steering wheel, accelerator, and brake. You do not need to know how fuel injection or the gearbox works.
- In Java you achieve abstraction with abstract classes and interfaces. The parent type declares WHAT (abstract methods); each subclass provides HOW (method bodies).
- Callers work with the abstract type (
Vehicle v), so the implementation can change without changing the caller.
abstract class Vehicle {
abstract void start(); // WHAT every vehicle can do
abstract void stop();
void honk() { // common behaviour, already implemented
System.out.println("Beep beep!");
}
}
class Car extends Vehicle {
@Override
void start() { System.out.println("Car: push button, engine starts"); } // HOW for a car
@Override
void stop() { System.out.println("Car: press brake pedal"); }
}
class Bike extends Vehicle {
@Override
void start() { System.out.println("Bike: kick start"); } // HOW for a bike
@Override
void stop() { System.out.println("Bike: squeeze brake lever"); }
}
public class AbstractionDemo {
public static void main(String[] args) {
Vehicle[] garage = { new Car(), new Bike() };
for (Vehicle v : garage) { // the driver only knows start, honk, stop
v.start();
v.honk();
v.stop();
}
}
} Abstraction in real life — show what it does, hide how it works
A car gives you a steering wheel and pedals, a remote gives you buttons, a coffee machine gives you one start button, and an ATM gives you a Withdraw option. The engine, circuits, heaters, and bank servers stay hidden. In Java, an abstract method is the WHAT and the subclass writes the HOW.
- You see: a small set of operations —
start(),stop(),withdraw(). - Hidden: how each operation works, written inside subclasses or implementing classes.
- Tools:
abstract class(0 to 100% abstraction) andinterface(full contract). - Benefit: callers use
Vehicle v; you can swapCarforBikewithout changing them.
Real-life examples of abstraction
- In every example the user works with a small, simple set of controls. The complex machinery stays hidden and can be replaced without retraining the user.
| Real-life object | What you use (essential) | What is hidden (implementation) | Java idea |
|---|---|---|---|
| Car | Steering, accelerator, brake, gear | Engine combustion, fuel injection, ABS logic | abstract class Vehicle with start(), stop() |
| TV remote | Power, volume, channel buttons | Circuit board, infrared signal codes | interface RemoteControl |
| ATM | Insert card, enter PIN, withdraw | Bank server, network, cash counting | interface Atm with withdraw(amount) |
| Coffee machine | Choose drink, press start | Water heating, grinding, pressure control | abstract class Beverage with brew() |
| Smartphone camera | Tap the shutter button | Sensor, autofocus, image processing | takePhoto() method |
| Write message, click Send | SMTP protocol, mail servers, routing | send(to, message) method | |
| Electric switch | Switch on, switch off | Wiring, current flow, power grid | interface Switchable |
| Online payment | Pay with UPI, card, or net banking | Encryption, bank APIs, fraud checks | abstract class Payment with pay() |
| Google Maps | Enter destination, follow route | GPS, shortest-path algorithms, traffic data | interface NavigationService |
| Washing machine | Choose mode, press start | Motor speed, water level, timers | abstract class WashProgram |
Why we need abstraction
- Reduces complexity: users of a class learn a few methods, not the whole implementation.
- Flexibility: swap one implementation for another (UPI to card payment, MySQL to PostgreSQL) without changing calling code.
- Loose coupling: code depends on the abstract type, not on concrete classes.
- Reusability: common code lives once in the abstract parent; only the changing parts are written in subclasses.
- Team work: one team writes against the interface while another team implements it.
- Supports polymorphism: one loop over
Vehicle[]works for cars, bikes, and buses.
How to achieve abstraction in Java
| Tool | How much abstraction | Keywords | Example |
|---|---|---|---|
| Abstract class | Partial (0 to 100%): mix abstract and concrete methods | abstract class, extends | abstract class Shape { abstract double area(); } |
| Interface | Full contract (100% before Java 8; default and static methods allowed since Java 8) | interface, implements | interface Payable { void pay(double amount); } |
| Access modifiers | Hide helper methods and fields inside a class | private, package-private | Private validation methods behind a public withdraw() |
| Packages and modules | Hide whole implementation classes | Package-private classes, module-info.java exports | Export only the API package, keep internal packages hidden |
Abstract class
- Declared with the
abstractkeyword. It cannot be instantiated withnew. - It can have abstract methods (no body) and concrete methods (with body), fields, constructors, and static members.
- A concrete subclass must implement every abstract method, otherwise the subclass must also be declared abstract.
- Real life: nobody buys "a payment". You pay by UPI, card, or net banking. Payment is an idea (abstract); UPI payment is a real thing (concrete).
abstract class Payment {
protected final double amount;
Payment(double amount) {
this.amount = amount;
}
abstract void pay(); // each payment type pays differently
void printReceipt() { // same for every payment type
System.out.println("Paid Rs." + amount + " via " + getClass().getSimpleName());
}
}
class UpiPayment extends Payment {
private final String upiId;
UpiPayment(double amount, String upiId) {
super(amount);
this.upiId = upiId;
}
@Override
void pay() { System.out.println("Sending UPI request to " + upiId); }
}
class CardPayment extends Payment {
private final String last4;
CardPayment(double amount, String last4) {
super(amount);
this.last4 = last4;
}
@Override
void pay() { System.out.println("Charging card ending " + last4); }
}
class NetBanking extends Payment {
NetBanking(double amount) { super(amount); }
@Override
void pay() { System.out.println("Redirecting to bank login"); }
}
public class PaymentDemo {
public static void main(String[] args) {
Payment[] payments = {
new UpiPayment(499, "asha@upi"),
new CardPayment(1299, "4321"),
new NetBanking(2500)
};
for (Payment p : payments) {
p.pay(); // caller does not know HOW each one pays
p.printReceipt();
}
// Payment p = new Payment(100); // ERROR: Payment is abstract; cannot be instantiated
}
} Abstract method
- A method declared with
abstractand no body. It ends with a semicolon:abstract void sound();. - It can exist only inside an abstract class (or an interface, where methods are abstract by default).
- It is a promise: every concrete subclass must provide the body.
- It cannot be
private,static, orfinal, because those can never be overridden.
abstract class Animal {
abstract void sound(); // OK: no body, ends with ;
// abstract void eat() { } // ERROR: abstract methods cannot have a body
// private abstract void sleep(); // ERROR: illegal combination of modifiers
// static abstract void info(); // ERROR: illegal combination of modifiers
// final abstract void run(); // ERROR: illegal combination of modifiers
}
class Dog extends Animal {
@Override
void sound() { System.out.println("Dog barks"); }
}
// class Cat extends Animal { } // ERROR: Cat is not abstract and does not override sound()
abstract class Bird extends Animal { } // OK: still abstract, may skip sound()
class Parrot extends Bird {
@Override
void sound() { System.out.println("Parrot talks"); }
}
public class AbstractMethodDemo {
public static void main(String[] args) {
Animal a = new Dog();
a.sound(); // Dog barks
new Parrot().sound(); // Parrot talks
}
} Rules of abstract classes and abstract methods
| Rule | Allowed? | Notes |
|---|---|---|
Create an object with new | No | Use a concrete subclass or an anonymous class |
| Reference variable of the abstract type | Yes | Shape s = new Circle(2); |
| Constructors | Yes | They run through super(...) when a subclass object is created |
| Instance and static fields | Yes | Shared state for all subclasses |
| Concrete (normal) methods | Yes | Common behaviour written once |
| Zero abstract methods | Yes | The class still cannot be instantiated |
main method inside an abstract class | Yes | An abstract class can be the program launcher |
final abstract class | No | final forbids extending, abstract requires it |
| Abstract method with a body | No | It must end with a semicolon |
private, static, or final abstract method | No | These cannot be overridden |
| Abstract method in a non-abstract class | No | The class must be declared abstract |
| Subclass skips an abstract method | Only if the subclass is abstract | Otherwise compile error |
| Override with wider access | Yes | protected abstract can become public in the child |
Abstraction with interfaces
- An interface is a pure contract: a list of methods that implementing classes must provide.
- Methods are
public abstractby default. Fields arepublic static finalconstants. - Since Java 8 an interface can have
defaultandstaticmethods; since Java 9 alsoprivatehelper methods. - A class can implement many interfaces, so unrelated classes can share a capability.
- Real life: one universal remote control works with a TV and an air conditioner. Each device decides how to react to the same buttons.
interface RemoteControl {
void powerOn(); // public abstract by default
void powerOff();
void setLevel(int level);
default void mute() { // Java 8+: shared default behaviour
setLevel(0);
}
}
class Television implements RemoteControl {
public void powerOn() { System.out.println("TV on"); }
public void powerOff() { System.out.println("TV off"); }
public void setLevel(int level) { System.out.println("TV volume " + level); }
}
class AirConditioner implements RemoteControl {
public void powerOn() { System.out.println("AC cooling started"); }
public void powerOff() { System.out.println("AC off"); }
public void setLevel(int level) { System.out.println("AC fan speed " + level); }
}
public class RemoteDemo {
public static void main(String[] args) {
RemoteControl[] devices = { new Television(), new AirConditioner() };
for (RemoteControl r : devices) {
r.powerOn();
r.mute(); // same button, each device decides how
r.powerOff();
}
}
} Differences between abstract class and interface
| Point | Abstract class | Interface |
|---|---|---|
| Keyword | abstract class | interface |
| Inherited with | extends (only one class) | implements (many); an interface can extends many interfaces |
| Methods | Abstract and concrete | Abstract, default, static, private (Java 9) |
| Fields | Any: instance and static, any access | Only public static final constants |
| Constructors | Yes | No |
| Instance state | Yes | No |
| Member access | Any modifier | Public by default (private helpers since Java 9) |
| Level of abstraction | Partial (0 to 100%) | Full contract |
| Multiple inheritance | No | Yes |
| Lambda support | No | Yes, if it is a functional interface (one abstract method) |
| Relationship | IS-A: Car is a Vehicle | CAN-DO: Car can be Insurable |
| Real-life analogy | A vehicle blueprint with a common engine number and chassis | A remote-control contract that any device can follow |
| Use when | Related classes share code and state | Unrelated classes share a capability |
Differences between abstraction and encapsulation
| Point | Abstraction | Encapsulation |
|---|---|---|
| Meaning | Hide complexity, show only essential operations | Hide data, control access to it |
| Focus | What an object does | How its data is protected |
| Level | Design level | Implementation level |
| Achieved by | Abstract classes and interfaces | private fields, getters, setters, access modifiers |
| Question it answers | What should the user see? | Who may read or change this data? |
| Real life | Driving with steering and pedals, without knowing the engine | The engine sealed under a locked bonnet |
| Java example | abstract void start(); | private double balance; with deposit() |
| Main benefit | Simpler use and replaceable implementations | Data safety and validation |
When to choose an abstract class or an interface
| Choose an abstract class when | Choose an interface when |
|---|---|
Subclasses share fields (state), like name or id | You only need method signatures (a contract) |
| You need a constructor to set up common data | Unrelated classes must share a role: Comparable, Runnable |
| You want to provide partial implementation | A class needs several roles at once |
You need non-public members (protected helpers) | You want lambdas (functional interface) |
| The classes form a clear IS-A family | You design a public API that others will implement |
| You use the template method pattern | You may later add a skeletal abstract class on top |
Advanced — Abstraction
Abstract class with state, constructor, and abstract method
- An abstract class constructor runs for every subclass object, so it is the right place for common setup like ID generation.
- Concrete methods in the parent can call abstract methods. The subclass version runs at runtime.
abstract class Employee {
private static int nextId = 1;
protected final int id;
protected final String name;
Employee(String name) { // runs for every subclass object
this.id = nextId++;
this.name = name;
}
abstract double monthlyPay(); // HOW is decided by subclasses
void printPayslip() { // concrete method calling an abstract one
System.out.printf("#%d %-6s Rs.%.2f%n", id, name, monthlyPay());
}
}
class Salaried extends Employee {
private final double annual;
Salaried(String name, double annual) {
super(name);
this.annual = annual;
}
@Override
double monthlyPay() { return annual / 12; }
}
class Hourly extends Employee {
private final double rate;
private final int hours;
Hourly(String name, double rate, int hours) {
super(name);
this.rate = rate;
this.hours = hours;
}
@Override
double monthlyPay() { return rate * hours; }
}
public class PayrollDemo {
public static void main(String[] args) {
Employee[] staff = { new Salaried("Asha", 600000), new Hourly("Ravi", 500, 120) };
for (Employee e : staff) {
e.printPayslip();
}
// #1 Asha Rs.50000.00
// #2 Ravi Rs.60000.00
}
} Template method pattern
- The abstract class fixes the order of steps in a
finalmethod. Subclasses fill in only the steps that change. - Real life: making tea and making coffee share boil water and pour into cup, but brewing and extras differ.
- Optional steps can be "hooks": concrete methods with a default that subclasses may override.
abstract class Beverage {
final void prepare() { // the fixed recipe; cannot be overridden
boilWater();
brew();
pourInCup();
if (wantsExtras()) {
addExtras();
}
}
private void boilWater() { System.out.println("Boiling water"); }
private void pourInCup() { System.out.println("Pouring into cup"); }
protected abstract void brew(); // step that changes
protected abstract void addExtras(); // step that changes
protected boolean wantsExtras() { // hook with a default
return true;
}
}
class Tea extends Beverage {
@Override protected void brew() { System.out.println("Steeping tea leaves"); }
@Override protected void addExtras() { System.out.println("Adding milk, sugar, and ginger"); }
}
class BlackCoffee extends Beverage {
@Override protected void brew() { System.out.println("Dripping coffee through a filter"); }
@Override protected void addExtras() { }
@Override protected boolean wantsExtras() { return false; }
}
public class TemplateDemo {
public static void main(String[] args) {
new Tea().prepare();
System.out.println("---");
new BlackCoffee().prepare();
}
} Abstraction in the JDK: program to the interface
- The JDK is full of abstractions. You call methods on the abstract type; the real class is hidden or replaceable.
- Declare variables and parameters with the abstract type (
List,Map) and choose the concrete class only atnew.
| Abstraction you use | Hidden implementations |
|---|---|
List | ArrayList, LinkedList, immutable lists from List.of |
Map | HashMap, TreeMap, LinkedHashMap |
java.sql.Connection | MySQL, PostgreSQL, Oracle driver classes |
InputStream | FileInputStream, ByteArrayInputStream, network streams |
ExecutorService | Thread pools, virtual-thread executors |
AbstractList, AbstractMap | Skeletal abstract classes that implement most methods for you |
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public class ProgramToInterface {
static int total(List<Integer> marks) { // works with ANY List
int sum = 0;
for (int m : marks) {
sum += m;
}
return sum;
}
public static void main(String[] args) {
List<Integer> a = new ArrayList<>(List.of(70, 85, 90));
List<Integer> b = new LinkedList<>(List.of(60, 75));
System.out.println(total(a)); // 245
System.out.println(total(b)); // 135
}
} Anonymous classes and lambdas for abstract types
- You cannot write
new Greeter()for an abstract class, but you can create an anonymous subclass on the spot. - An interface with exactly one abstract method (functional interface) can be implemented with a lambda or method reference.
- Lambdas work only with interfaces, never with abstract classes.
abstract class Greeter {
abstract void greet(String name);
}
interface Calculator {
int apply(int a, int b); // one abstract method: functional interface
}
public class AnonymousDemo {
public static void main(String[] args) {
Greeter g = new Greeter() { // anonymous subclass of an abstract class
@Override
void greet(String name) { System.out.println("Hello, " + name); }
};
g.greet("Asha");
Calculator add = (a, b) -> a + b; // lambda
Calculator max = Math::max; // method reference
System.out.println(add.apply(4, 5)); // 9
System.out.println(max.apply(4, 5)); // 5
// Greeter bad = name -> System.out.println(name); // ERROR: lambdas need an interface
}
} Sealed abstract classes (Java 17+)
sealed abstract class Shape permits Circle, Square, Trianglelimits which classes may extend the abstraction.- Each permitted subclass must be
final,sealed, ornon-sealed. - With Java 21 pattern matching, a
switchover a sealed abstract type is checked for completeness by the compiler.
sealed abstract class Shape permits Circle, Square, Triangle {
abstract double area();
}
final class Circle extends Shape {
private final double r;
Circle(double r) { this.r = r; }
double area() { return Math.PI * r * r; }
}
final class Square extends Shape {
private final double s;
Square(double s) { this.s = s; }
double area() { return s * s; }
}
non-sealed class Triangle extends Shape {
private final double b, h;
Triangle(double b, double h) { this.b = b; this.h = h; }
double area() { return 0.5 * b * h; }
}
public class SealedShapes {
static String describe(Shape s) {
return switch (s) { // Java 21: exhaustive over permitted types
case Circle c -> "circle";
case Square q -> "square";
case Triangle t -> "triangle";
};
}
public static void main(String[] args) {
Shape[] shapes = { new Circle(1), new Square(2), new Triangle(3, 4) };
for (Shape s : shapes) {
System.out.printf("%s area = %.2f%n", describe(s), s.area());
}
}
} Interface plus skeletal abstract class
- Large libraries combine both tools: an interface defines the contract, and an abstract class implements the common parts.
- Implementers extend the skeleton and write only the unique methods. The JDK does this with
ListandAbstractList.
interface Shape {
double area();
double perimeter();
String name();
}
abstract class AbstractShape implements Shape { // shared code written once
@Override
public String toString() {
return String.format("%s: area=%.2f, perimeter=%.2f", name(), area(), perimeter());
}
}
class Rectangle extends AbstractShape {
private final double w, h;
Rectangle(double w, double h) { this.w = w; this.h = h; }
public double area() { return w * h; }
public double perimeter() { return 2 * (w + h); }
public String name() { return "Rectangle"; }
}
public class SkeletalDemo {
public static void main(String[] args) {
Shape s = new Rectangle(3, 4);
System.out.println(s); // Rectangle: area=12.00, perimeter=14.00
}
} Abstraction design mistakes
| Mistake | Problem | Better |
|---|---|---|
| Making everything abstract "to be OOP" | Extra layers with only one implementation | Start concrete; abstract when a second implementation appears |
| One huge interface with many methods | Implementers write empty methods they do not need | Split into small, focused interfaces |
| Leaky abstraction: returning internal lists | Callers depend on and change internals | Return copies or read-only views |
| Calling abstract methods from the constructor | Subclass fields are not initialized yet | Call them after construction |
Checking instanceof on the abstraction | Defeats the purpose of abstraction | Add a method to the abstract type instead |
Vague names like AbstractManagerHelperImpl | Role is unclear | Role names: Payment, Shape, Repository |
Tricky Interview Points
Q1) What is abstraction in Java?
Answer Showing only the essential features of an object and hiding implementation details. Java achieves it with abstract classes and interfaces.
Q2) Give a real-life example of abstraction.
Answer Driving a car: you use the steering, accelerator, and brake without knowing how the engine works. Other examples are a TV remote, an ATM, and a coffee machine.
Q3) How is abstraction achieved in Java?
Answer With abstract classes (partial abstraction, 0 to 100%) and interfaces (a full contract). Access modifiers and packages support it by hiding helpers.
Q4) What is an abstract class?
Answer A class declared with abstract that cannot be instantiated. It can contain abstract and concrete methods, fields, constructors, and static members.
Q5) What is an abstract method?
Answer A method with the abstract keyword and no body, ending with a semicolon. Every concrete subclass must override it.
Q6) Can we create an object of an abstract class?
Answer No. But you can declare a reference of the abstract type pointing to a concrete subclass, or create an anonymous subclass.
Q7) Can an abstract class have a constructor?
Answer Yes. It runs through super(...) when a subclass object is created, usually to initialize common fields.
Q8) Must an abstract class have at least one abstract method?
Answer No. An abstract class with zero abstract methods is legal; it simply cannot be instantiated.
Q9) Can a non-abstract class have an abstract method?
Answer No. If a class declares or inherits an unimplemented abstract method, the class itself must be declared abstract.
Q10) Can an abstract method be private, static, or final?
Answer No. These modifiers prevent overriding, while abstract requires a subclass to override the method. The compiler reports an illegal combination of modifiers.
Q11) Can an abstract class be final?
Answer No. final prevents extending, but an abstract class is useful only when extended.
Q12) Can an abstract class have a main method?
Answer Yes. main is static, so the JVM can run it without creating an object of the abstract class.
Q13) What is the difference between an abstract class and an interface?
Answer An abstract class can have state, constructors, and any access modifiers, but a class can extend only one. An interface has no instance state or constructors, but a class can implement many and it supports lambdas.
Q14) What is the difference between abstraction and encapsulation?
Answer Abstraction hides complexity and shows what an object does. Encapsulation hides data and controls who can change it. Abstraction is a design idea; encapsulation is implemented with private fields and methods.
Q15) Can an interface have method bodies?
Answer Yes, since Java 8 through default and static methods, and since Java 9 through private methods. Abstract methods still have no body.
Q16) Can we use a lambda for an abstract class?
Answer No. Lambdas only implement functional interfaces. For an abstract class you need a named or anonymous subclass.
Q17) What is the template method pattern?
Answer An abstract class defines a final method with the fixed order of steps and leaves some steps abstract for subclasses to implement.
Q18) Is it possible to achieve 100% abstraction with an abstract class?
Answer Yes, if all its methods are abstract, but an interface is the usual choice for a pure contract because a class can implement many interfaces.
Simple Programs
Bank interest rates with an abstract class
abstract class Bank {
abstract double rateOfInterest();
double yearlyInterest(double amount) {
return amount * rateOfInterest() / 100;
}
}
class Sbi extends Bank {
@Override double rateOfInterest() { return 6.5; }
}
class Hdfc extends Bank {
@Override double rateOfInterest() { return 7.0; }
}
class Icici extends Bank {
@Override double rateOfInterest() { return 7.25; }
}
public class BankDemo {
public static void main(String[] args) {
Bank[] banks = { new Sbi(), new Hdfc(), new Icici() };
for (Bank b : banks) {
System.out.println(b.getClass().getSimpleName() + ": "
+ b.rateOfInterest() + "% -> Rs." + b.yearlyInterest(100000));
}
}
} Notification sender with an interface
interface Notifier {
void send(String to, String message);
}
class EmailNotifier implements Notifier {
public void send(String to, String message) {
System.out.println("Email to " + to + ": " + message);
}
}
class SmsNotifier implements Notifier {
public void send(String to, String message) {
System.out.println("SMS to " + to + ": " + message);
}
}
class WhatsAppNotifier implements Notifier {
public void send(String to, String message) {
System.out.println("WhatsApp to " + to + ": " + message);
}
}
public class NotifyDemo {
static void broadcast(Notifier[] channels, String to, String msg) {
for (Notifier n : channels) {
n.send(to, msg); // caller never knows HOW each channel delivers
}
}
public static void main(String[] args) {
Notifier[] channels = { new EmailNotifier(), new SmsNotifier(), new WhatsAppNotifier() };
broadcast(channels, "Asha", "Your order has shipped");
}
} ATM: public operations, hidden steps
interface Atm {
void withdraw(int pin, double amount);
}
class SbiAtm implements Atm {
private double balance = 10000;
private static final int PIN = 1234;
@Override
public void withdraw(int pin, double amount) {
if (!verifyPin(pin)) {
System.out.println("Wrong PIN");
return;
}
if (!hasFunds(amount)) {
System.out.println("Insufficient balance");
return;
}
balance -= amount;
dispenseCash(amount);
}
private boolean verifyPin(int pin) { return pin == PIN; } // hidden
private boolean hasFunds(double amount) { return amount <= balance; } // hidden
private void dispenseCash(double amount) { // hidden
System.out.println("Please collect Rs." + amount + ". Balance: Rs." + balance);
}
}
public class AtmDemo {
public static void main(String[] args) {
Atm atm = new SbiAtm(); // user sees only withdraw()
atm.withdraw(1111, 500); // Wrong PIN
atm.withdraw(1234, 20000); // Insufficient balance
atm.withdraw(1234, 2500); // Please collect Rs.2500.0. Balance: Rs.7500.0
}
} Game template: Cricket and Football
abstract class Game {
final void play() {
initialize();
startPlay();
endPlay();
}
abstract void initialize();
abstract void startPlay();
abstract void endPlay();
}
class Cricket extends Game {
void initialize() { System.out.println("Cricket: toss done, pitch ready"); }
void startPlay() { System.out.println("Cricket: first ball bowled"); }
void endPlay() { System.out.println("Cricket: match over after 20 overs"); }
}
class Football extends Game {
void initialize() { System.out.println("Football: teams on the field"); }
void startPlay() { System.out.println("Football: kick-off"); }
void endPlay() { System.out.println("Football: final whistle after 90 minutes"); }
}
public class GameDemo {
public static void main(String[] args) {
Game[] games = { new Cricket(), new Football() };
for (Game g : games) {
g.play();
System.out.println();
}
}
} Shapes: abstract class with constructor and concrete method
abstract class Shape {
private final String color;
Shape(String color) {
this.color = color;
}
abstract double area();
void describe() {
System.out.printf("%s %s, area = %.2f%n", color, getClass().getSimpleName(), area());
}
}
class Circle extends Shape {
private final double r;
Circle(String color, double r) { super(color); this.r = r; }
@Override double area() { return Math.PI * r * r; }
}
class Rectangle extends Shape {
private final double w, h;
Rectangle(String color, double w, double h) { super(color); this.w = w; this.h = h; }
@Override double area() { return w * h; }
}
class Triangle extends Shape {
private final double b, h;
Triangle(String color, double b, double h) { super(color); this.b = b; this.h = h; }
@Override double area() { return 0.5 * b * h; }
}
public class ShapeDemo {
public static void main(String[] args) {
Shape[] shapes = { new Circle("Red", 2), new Rectangle("Blue", 3, 4), new Triangle("Green", 6, 5) };
for (Shape s : shapes) {
s.describe();
}
}
} Documents: interface + abstract class together
interface Printable {
void print();
}
abstract class Document implements Printable {
protected final String title;
Document(String title) {
this.title = title;
}
abstract String format();
@Override
public void print() { // common printing logic
System.out.println("Printing [" + format() + "] " + title);
}
}
class PdfDocument extends Document {
PdfDocument(String title) { super(title); }
@Override String format() { return "PDF"; }
}
class WordDocument extends Document {
WordDocument(String title) { super(title); }
@Override String format() { return "DOCX"; }
}
public class PrintDemo {
public static void main(String[] args) {
Printable[] queue = { new PdfDocument("Java Notes"), new WordDocument("Resume") };
for (Printable p : queue) {
p.print();
}
}
} Problem Solving Tricks
- Remember: abstraction = WHAT, implementation = HOW. Abstract methods are the WHAT; subclasses write the HOW.
- Abstract class = 0 to 100% abstraction; interface = full contract. A class extends one abstract class but implements many interfaces.
- An abstract method ends with a semicolon and has no braces.
- abstract never combines with
private,static, orfinalon a method, or withfinalon a class. - Declare variables with the abstract type:
List<String> names = new ArrayList<>();. - Use an abstract class when subclasses share fields or a constructor; use an interface for a role.
- Template method: put the fixed algorithm in a
finalmethod and leave steps abstract. - Lambdas work only with functional interfaces, never with abstract classes.
- Do not create an abstraction until you have (or clearly expect) two implementations.
- Name abstractions by role:
Payment,Shape,Notifier, notAbstractThingImpl.
Practice Programs List
- Create
abstract class Vehiclewithabstract void start()and implement it inCar,Bike, andBus. - Write a table of five real-life objects with what the user sees and what is hidden, then code one of them.
- Create
abstract class EmployeewithmonthlyPay()and subclassesSalariedandHourly. - Give the abstract class a constructor that stores
name, and print it from each subclass. - Try
new Employee("x")and write down the exact compiler error. - Try declaring an abstract method as
private,static, andfinal, and record each error. - Write
abstract class BankwithrateOfInterest()and three bank subclasses. - Create
interface RemoteControlwith adefault mute()method and implement it for a TV and a fan. - Write the same payment design once with an abstract class and once with an interface. Which fits better and why?
- Implement the template method pattern for making tea and coffee.
- Create an anonymous subclass of an abstract class inside
main. - Write a functional interface
Operationand implement add, subtract, and multiply with lambdas. - Create a sealed abstract class
Shapewith three permitted subclasses and an exhaustive switch. - Write a method
total(List<Integer>)and call it with anArrayListand aLinkedList.