Muhammad Fari Madyan
Hire me
Java basics · part 17 of 21

Learn Java from Scratch Part 17: Abstract Classes and Interfaces — Contracts, implements & default

The seventeenth part of a Java series: an abstract class as a half-finished cutter, an interface as a plug standard, implements and several interfaces at once, default methods, when to use which, a shop cashier with cash and an e-wallet, and three contract traps.

Muhammad Fari Madyan

· 8 min read

Baca dalam Bahasa Indonesia →

Introduction: A Socket That Does Not Care

You can plug your phone charger in at home, at the office, or in a café. The wall socket does not care whether you plug in a phone, a laptop, or a fan.

As long as the plug fits, the electricity flows.

In this part we create a contract like that in Java: abstract classes and interfaces.

After this part, you will be able to:

  1. Create a half-finished cutter with abstract.
  2. Create a contract for an ability with interface and implements.
  3. Choose when to use an abstract class and when to use an interface.

Answer to the Part 16 Challenge

The question: X x = new Y();, then x.nama(). What is the output?

The answer is C: Anak.

The variable has the type X, but the real object is a Y. Java runs the version of the real object, so the result is Anak.

If you answered C, well done!


1. The Problem: A Shape That Means Nothing

In Part 16, the class Bentuk had a method luas() that returned 0. But a "shape" in general has no sensible area.

There are two more problems:

  • Anyone can write new Bentuk(), a plain shape that means nothing.
  • A child class can forget to rewrite luas(), and nobody complains.

We need a way to say: every shape must have an area, but each shape decides how to calculate it.


2. Answer One: An Abstract Class, a Half-Finished Cutter

The file Bentuk.java:

JAVA
public abstract class Bentuk {
    public abstract double luas();

    public void info() {
        IO.println("Luas: " + luas());
    }
}
PieceMeaning
abstract class BentukA half-finished cutter. You cannot make it directly with new.
abstract double luas();A method with no body, just a semicolon. Every child must fill it in.
info()A normal method. An abstract class can still have methods with a body.

The files Lingkaran.java and Persegi.java from Part 16 do not need any change. Both already extends Bentuk and already fill in luas(). The file Main.java:

JAVA
void main() {
    Bentuk[] semua = {new Lingkaran(10), new Persegi(4)};

    for (Bentuk b : semua) {
        b.info();
    }
}
TEXT
Luas: 314.0
Luas: 16.0

Look at info(). That method belongs to Bentuk, but it calls the luas() of the real object. This is polymorphism from Part 16 again.


3. Answer Two: An Interface, a Plug Standard

Picture the standard for an electric plug. That standard does not care what the device is. It only decides the shape of the plug.

In Java, this standard is called an interface.

An interface is like a plug standard: Hp and Laptop are not related, but both meet the BisaDicas contract

Click the diagram to open it in full size.

The file BisaDicas.java. Bisa dicas means "can be charged":

JAVA
public interface BisaDicas {
    void cas();
}

The file BisaDiputar.java. Bisa diputar means "can play" (music):

JAVA
public interface BisaDiputar {
    void putar();
}

The file Hp.java. Hp is what Indonesians call a mobile phone:

JAVA
public class Hp implements BisaDicas, BisaDiputar {
    @Override
    public void cas() {
        IO.println("Hp dicas lewat USB-C");
    }

    @Override
    public void putar() {
        IO.println("Hp memutar lagu");
    }
}

The file Laptop.java:

JAVA
public class Laptop implements BisaDicas {
    @Override
    public void cas() {
        IO.println("Laptop dicas lewat adaptor");
    }
}

The file Main.java. Alat means "device":

JAVA
void main() {
    BisaDicas[] alat = {new Hp(), new Laptop()};

    for (BisaDicas a : alat) {
        a.cas();
    }

    BisaDiputar pemutar = new Hp();
    pemutar.putar();
}
TEXT
Hp dicas lewat USB-C
Laptop dicas lewat adaptor
Hp memutar lagu

The lines say "The phone is charged through USB-C", "The laptop is charged through an adapter" and "The phone plays a song".

Hp and Laptop are not related. But both meet the same contract, so they fit into one BisaDicas array and get charged in one loop.

The word for meeting a contract is implements.

Remember the rule in Part 15: a class can have only one parent. But a class can meet many interfaces at the same time. Hp meets both BisaDicas and BisaDiputar.

Let us look into memory. There is only one phone object in the warehouse. But it can be held with a ticket of type BisaDicas, or with a ticket of type BisaDiputar. Each ticket only sees the buttons in its own contract.


4. default Methods: A Contract with a Body

An interface can also have a default method, which is a method that already has a body. A class that meets the contract gets it for free, unless it wants to rewrite it.

You see an example in the challenge at the end of this part.


5. When to Use Which?

UseForExample
An abstract classA real family that shares fields and codeGeometric shapes
An interfaceAn ability that anyone can have, from any familyCan be charged, can pay, can play music

In real jobs, interfaces are used all the time. They let you swap parts of a program without disturbing each other. The next example shows how.


6. A Real Example: A Shop Cashier

The file Pembayaran.java. Pembayaran means "payment", bayar means "pay" and jumlah means "amount":

JAVA
public interface Pembayaran {
    boolean bayar(int jumlah);
}

The file Tunai.java. Tunai means "cash":

JAVA
public class Tunai implements Pembayaran {
    private int uang;

    public Tunai(int uang) {
        this.uang = uang;
    }

    @Override
    public boolean bayar(int jumlah) {
        return uang >= jumlah;
    }
}

The file EWallet.java:

JAVA
public class EWallet implements Pembayaran {
    private int saldo;

    public EWallet(int saldo) {
        this.saldo = saldo;
    }

    @Override
    public boolean bayar(int jumlah) {
        if (saldo >= jumlah) {
            saldo -= jumlah;
            return true;
        }
        return false;
    }
}

The file Main.java. Kasir means "cashier", cara means "way" and harga means "price":

JAVA
void kasir(Pembayaran cara, int harga) {
    if (cara.bayar(harga)) {
        IO.println("Pembayaran " + harga + " berhasil");
    } else {
        IO.println("Pembayaran " + harga + " gagal");
    }
}

void main() {
    kasir(new Tunai(50_000), 30_000);
    kasir(new EWallet(20_000), 30_000);
}
TEXT
Pembayaran 30000 berhasil
Pembayaran 30000 gagal

Berhasil means "succeeded" and gagal means "failed". The cash buyer brings 50,000 rupiah for a 30,000 purchase, so it succeeds. The e-wallet has a balance of 20,000, which is not enough, so it fails.

The method kasir does not know whether the buyer pays in cash or with an e-wallet. It only knows the contract.

A new way to pay tomorrow, such as QRIS, the Indonesian QR payment? Just create a new class that implements Pembayaran. The cashier code does not change.


7. Three Contract Traps

Trap one: making an abstract class directly.

JAVA
void main() {
    Bentuk b = new Bentuk();
}
TEXT
Main.java:2: error: Bentuk is abstract; cannot be instantiated
    Bentuk b = new Bentuk();
               ^
1 error
error: compilation failed

A half-finished cutter cannot make anything. Create an object from a child, for example new Lingkaran(10).

Trap two: forgetting to fill in a contract method.

JAVA
public class Hp implements BisaDicas {
}
TEXT
Hp.java:1: error: Hp is not abstract and does not override abstract method cas() in BisaDicas
public class Hp implements BisaDicas {
       ^
1 error

As soon as you write implements, you promise to fill in every method of that contract.

Trap three: forgetting public.

JAVA
public class Hp implements BisaDicas {
    void cas() {
        IO.println("Hp dicas");
    }
}
TEXT
Hp.java:2: error: cas() in Hp cannot implement cas() in BisaDicas
    void cas() {
         ^
  attempting to assign weaker access privileges; was public
1 error

A method in an interface is always public, even when the word is not written. So the version in the class must be public too.

The second and third error messages above come from javac. With java Main.java, the message is the same, but the file name includes its folder.


Summary

  1. An abstract class is a half-finished cutter. You cannot make it directly, and its abstract methods must be filled in by the children.
  2. An interface is a contract for an ability. One class can meet many interfaces.
  3. Use an abstract class for a family, and an interface for an ability across families.

Challenge

The file Sapa.java. Sapa means "greet":

JAVA
public interface Sapa {
    default String halo() {
        return "Halo";
    }
}

The file Robot.java:

JAVA
public class Robot implements Sapa {
}

The file Main.java:

JAVA
void main() {
    IO.println(new Robot().halo());
}

What is the output?

  • A. An error.
  • B. Halo
  • C. null

Try to answer before you run it. I explain the answer at the start of Part 18.


Conclusion & What's Next

You can now create contracts. If you remember only one thing, remember the wall socket. It does not care what the device is, as long as the plug fits.

In Part 18, we learn to catch problems before the program falls over. There is a red ball thrown up the pile of trays, and there is a net to catch it.

See you in Part 18. Get your coffee ready. Hot chocolate is fine too.

ShareLinkedInXWhatsApp

Written by Muhammad Fari Madyan

Senior Backend Engineer and co-founder of LampungDev. I write up what I build so others can learn from it.

Work with me
← part 16Polymorphismpart 18 →Exceptions

Muhammad Fari Madyan

Senior Backend Engineer building real-time, high-concurrency systems that hold up in production. Co-founder of LampungDev. Based in Bandar Lampung, Indonesia (UTC+7), working remote.

Work

Case studiesCahTixExam platform, 4 stacksOpen source

© 2026 Muhammad Fari Madyan

Designed and built by Muhammad Fari Madyan