Core Java

core12Polymorphism

Path
pkg1core/core12Polymorphism.java
Package
pkg1core
Study order
13
Run
Single-file source launch
Command
java pkg1core/core12Polymorphism.java
Lesson
Back to the chapter

There is no in-browser runner. This is the file from the curriculum, unchanged.

pkg1core/core12Polymorphism.java
1package pkg1core;2 3/*4 * core12Polymorphism.java5 * -----------------6 * Compile-time (overloading) vs runtime (overriding / dynamic dispatch).7 *8 * EXPLANATION:9 *  - Overloading: same method name, different parameters; chosen at COMPILE time.10 *  - Overriding: subclass redefines a method; chosen at RUNTIME by actual type.11 *  - Dynamic dispatch enables programming to an abstraction.12 */13public class core12Polymorphism {14 15    // --- Overloading (static polymorphism) ---16    static String describe(int x)    { return "int: " + x; }17    static String describe(double x) { return "double: " + x; }18    static String describe(String x) { return "String: " + x; }19 20    // --- Overriding (dynamic polymorphism) ---21    abstract static class Shape { abstract double area(); }22    static class Circle extends Shape {23        double r; Circle(double r){ this.r = r; }24        double area(){ return Math.PI * r * r; }25    }26    static class Square extends Shape {27        double s; Square(double s){ this.s = s; }28        double area(){ return s * s; }29    }30 31    public static void main(String[] args) {32        // Overloading resolved by argument type at compile time33        System.out.println(describe(10));34        System.out.println(describe(3.14));35        System.out.println(describe("hi"));36 37        // Overriding: same call, different behavior by runtime type38        Shape[] shapes = { new Circle(2), new Square(3) };39        for (Shape sh : shapes) {40            System.out.printf("%s area = %.2f%n", sh.getClass().getSimpleName(), sh.area());41        }42    }43}