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:
- Create a half-finished cutter with
abstract. - Create a contract for an ability with
interfaceandimplements. - 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:
public abstract class Bentuk {
public abstract double luas();
public void info() {
IO.println("Luas: " + luas());
}
}
| Piece | Meaning |
|---|---|
abstract class Bentuk | A 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:
void main() {
Bentuk[] semua = {new Lingkaran(10), new Persegi(4)};
for (Bentuk b : semua) {
b.info();
}
}
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.
Click the diagram to open it in full size.
The file BisaDicas.java. Bisa dicas means "can be charged":
public interface BisaDicas {
void cas();
}
The file BisaDiputar.java. Bisa diputar means "can play" (music):
public interface BisaDiputar {
void putar();
}
The file Hp.java. Hp is what Indonesians call a mobile phone:
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:
public class Laptop implements BisaDicas {
@Override
public void cas() {
IO.println("Laptop dicas lewat adaptor");
}
}
The file Main.java. Alat means "device":
void main() {
BisaDicas[] alat = {new Hp(), new Laptop()};
for (BisaDicas a : alat) {
a.cas();
}
BisaDiputar pemutar = new Hp();
pemutar.putar();
}
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?
| Use | For | Example |
|---|---|---|
| An abstract class | A real family that shares fields and code | Geometric shapes |
| An interface | An ability that anyone can have, from any family | Can 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":
public interface Pembayaran {
boolean bayar(int jumlah);
}
The file Tunai.java. Tunai means "cash":
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:
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":
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);
}
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.
void main() {
Bentuk b = new Bentuk();
}
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.
public class Hp implements BisaDicas {
}
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.
public class Hp implements BisaDicas {
void cas() {
IO.println("Hp dicas");
}
}
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
- An abstract class is a half-finished cutter. You cannot make it directly, and its
abstractmethods must be filled in by the children. - An interface is a contract for an ability. One class can meet many interfaces.
- Use an abstract class for a family, and an interface for an ability across families.
Challenge
The file Sapa.java. Sapa means "greet":
public interface Sapa {
default String halo() {
return "Halo";
}
}
The file Robot.java:
public class Robot implements Sapa {
}
The file Main.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.

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.

