CJCoding With Joseph
15free / daySign inCreate account

Mastering Java - Full Guide

Interfaces

Everything On Classes

In the last section, we used abstract classes to enforce structure and shared behavior between multiple account types. But what if we don’t want to define any shared code at all, and just force certain methods to exist? That’s where interfaces come in.


What Is an Interface?

An interface is a contract. It tells a class: If you want to implement me, you must provide your own versions of the listed methods.

An interface can also include constants, which are public static final by default. Here’s an example:

public interface Payable {
    int BASE_RATE = 15; // This is automatically public static final

    double calculatePay();
    String getPayeeName();
}

Any class that says it "implements Payable" must include calculatePay() and getPayeeName(). It will also have access to BASE_RATE, but it cannot change it.

⚠️ Interfaces don’t use extends. Instead, a class must use implements.

Members only

Keep reading this lesson

You've reached the end of the free preview. Unlock the rest of this lesson plus 14 more lessons in Mastering Java - Full Guide.

  • Unlimited coding questions
  • Unlimited access to all classroom material
  • Weekly live call for questions and guidance
  • 3,000 AI tutor tokens / month
  • Personal SQL database (3 MB)
  • Progress tracking

Cancel any time.