Core Java
core13AbstractionDemo
- Path
- pkg1core/core13AbstractionDemo.java
- Package
- pkg1core
- Study order
- 14
- Run
- Single-file source launch
- Command
- java pkg1core/core13AbstractionDemo.java
- Lesson
- Back to the chapter
There is no in-browser runner. This is the file from the curriculum, unchanged.
1package pkg1core;2 3/*4 * core13AbstractionDemo.java5 * --------------------6 * Abstract classes: partial implementation + enforced contract.7 *8 * EXPLANATION:9 * - An abstract class cannot be instantiated; it may hold state and concrete10 * methods plus abstract methods that subclasses MUST implement.11 * - Use an abstract class (vs interface) when you need shared state/behavior.12 * - Template Method pattern: a concrete method orchestrates abstract steps.13 */14public class core13AbstractionDemo {15 16 abstract static class Payment {17 protected final double amount;18 Payment(double amount) { this.amount = amount; }19 20 // Template method: fixed algorithm, variable steps21 final void process() {22 validate();23 System.out.println("Charging " + amount + " via " + method());24 authorize();25 System.out.println("Done.\n");26 }27 void validate() { if (amount <= 0) throw new IllegalArgumentException("amount<=0"); }28 29 // Steps subclasses must define30 abstract String method();31 abstract void authorize();32 }33 34 static class CardPayment extends Payment {35 CardPayment(double a){ super(a); }36 String method() { return "Credit Card"; }37 void authorize() { System.out.println(" contacting card network..."); }38 }39 static class UpiPayment extends Payment {40 UpiPayment(double a){ super(a); }41 String method() { return "UPI"; }42 void authorize() { System.out.println(" verifying VPA..."); }43 }44 45 public static void main(String[] args) {46 Payment[] payments = { new CardPayment(120.0), new UpiPayment(45.5) };47 for (Payment p : payments) p.process();48 // new Payment(10); // ERROR: cannot instantiate abstract class49 }50}