Fundamentals 3 min read

Using Interfaces as Types in Java: A Beginner’s Guide

This note explains how Java interfaces define new data types, how variables of an interface type must reference objects implementing that interface, and demonstrates the concept with a concrete example that casts objects to a Compare interface to select the larger one.

Lisa Notes
Lisa Notes
Lisa Notes
Using Interfaces as Types in Java: A Beginner’s Guide

In Java, any place that expects a data type can also accept an interface name because each interface defines a new type; defining a new interface therefore creates a new type.

To declare a variable of an interface type, the assigned reference must be an instance of a class that implements the interface. For example, to find the larger of two objects, both objects must be instances of classes that implement the Compare interface.

public Object isCompare(Object o1, Object o2) {
    // Cast o1 to Compare
    Compare obj1 = (Compare) o1;
    // Cast o2 to Compare
    Compare obj2 = (Compare) o2;
    // Compare the two objects
    if (obj1.isCompare(obj2) > 0)
        return o1;
    else
        return o2;
}

The example casts the parameters to Compare, allowing the isCompare method to be invoked; the method returns the object that is considered larger according to the interface’s comparison logic.

When a class implements Compare, its instances can be treated both as their concrete class type and as a Compare type, thus possessing both the class’s behavior and the behavior defined by the interface.

This capability aligns with Java’s “write once, run anywhere” principle, making it well‑suited for developing pure object‑oriented programs in distributed environments.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaProgramming FundamentalsOOPTypeInterfaceCasting
Lisa Notes
Written by

Lisa Notes

Lisa's notes: musings on daily life, work, study, personal growth, and casual reflections.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.