bhylu.com

Advertisements

Java Call Through a Shared Contract

Polymorphism lets code call an instance method through a parent type while the object’s runtime type supplies the implementation.

Understand the idea

The declared type determines which operations a caller is allowed to request. For an overridden instance method, the receiver’s actual class selects the implementation. This does not apply in the same way to static method hiding or overloaded parameter resolution. Program against a meaningful contract so a caller does not need a growing chain of type checks whenever a new implementation is introduced.

Run it locally

Use a local JDK 21 or newer. Save the complete example as Main.java in a separate lab folder, then compile and run it with the commands below. Java examples do not run in Bhylu’s browser playground. The -ea option enables assertion checks used by some lessons.

JDK and terminal setup

javac --release 21 -encoding UTF-8 -d out Main.java
java -ea -cp out Main

A worked example

Java 21+ · Main.java

public class Main {
    interface FeePolicy { int centsFor(int seats); }
    static class GroupFee implements FeePolicy {
        @Override public int centsFor(int seats) { return seats * 350; }
    }

    public static void main(String[] args) {
        FeePolicy policy = new GroupFee();
        System.out.println(policy.centsFor(4));
    }
}

Expected output

1400

policy is declared as FeePolicy, but its object is a GroupFee. The call uses the implementation that object provides. The caller does not need to know the implementation’s private details. This example separates a price policy from a booking record, allowing each to change for a different reason.

Check the official Java documentation for detailed contracts and supported options.