Introduction: A Birthday Cake Is Still a Cake
A birthday cake is still a cake. It has a flavour, and it can show itself. The difference is the writing on top.
Do we need to rewrite the cake cutter from zero? No. We inherit the old cutter, then add the decoration.
In this part we meet inheritance.
After this part, you will be able to:
- Create a child class with
extends. - Use
superto call the constructor and the methods of the parent. - Decide when inheritance is a good fit, and when it is not.
Answer to the Part 14 Challenge
The question: setTerang(120), then setTerang(80), then setTerang(-10). What is the output?
The answer is B: 80.
120 and -10 are rejected by the rule in the setter, because they are outside 0 to 100. Only 80 goes in.
If you answered B, well done!
1. The Problem: The Same Code in Many Places
Programs often have kinds of things that are alike:
- a normal cake and a birthday cake,
- an employee and a manager,
- a vehicle and a motorbike.
If every class is written from zero, the same code is copied into many places. When something changes, every copy must be changed one by one.
2. Inheritance Is a Parent Cutter and a Child Cutter
Picture the basic cake cutter as the parent. From that cutter, we make a child cutter. The shape is the same, plus a place for the writing.
The child cutter automatically inherits everything its parent has. It only needs to add the new parts.
| Term | Meaning | In our example |
|---|---|---|
| Superclass | The parent class | Kue |
| Subclass | The child class | KueUlangTahun |
extends | The word that means "is a child of" | KueUlangTahun extends Kue |
Kue means "cake" and kue ulang tahun means "birthday cake".
Click the diagram to open it in full size.
3. Writing the Parent and the Child
We keep the rule from Part 14: one class, one file. Prepare one folder with three files.
The file Kue.java, the parent. rasa is the flavour:
public class Kue {
private String rasa;
public Kue(String rasa) {
this.rasa = rasa;
}
public String getRasa() {
return rasa;
}
public void tampil() {
IO.println("Kue rasa " + rasa);
}
}
The file KueUlangTahun.java, the child. ucapan is the greeting written on the cake:
public class KueUlangTahun extends Kue {
private String ucapan;
public KueUlangTahun(String rasa, String ucapan) {
super(rasa);
this.ucapan = ucapan;
}
public void tampil() {
super.tampil();
IO.println("Tulisan: " + ucapan);
}
}
The file Main.java:
void main() {
Kue biasa = new Kue("Keju");
biasa.tampil();
KueUlangTahun ultah = new KueUlangTahun("Cokelat", "Selamat ulang tahun, Rani!");
ultah.tampil();
IO.println(ultah.getRasa());
}
Run it with java Main.java:
Kue rasa Keju
Kue rasa Cokelat
Tulisan: Selamat ulang tahun, Rani!
Cokelat
The greeting means "Happy birthday, Rani!", and tulisan means "writing".
Look at the last line. We never wrote getRasa() in KueUlangTahun, but the object ultah can call it. That method is inherited from Kue.
Inside KueUlangTahun, we only write what is new: the field ucapan and the way to show the writing.
4. The Word super: Call the Parent's Part
super is used in two places.
In the constructor: super(rasa);
A birthday cake needs a flavour, but the flavour is handled by the parent's constructor. So on the first line of the child's constructor, we write super(rasa);. It means: run the parent's assembly line first.
In a method: super.tampil();
A child may rewrite a method of its parent. The tampil() of KueUlangTahun calls super.tampil() to print the flavour, then adds the line with the writing.
Now we look into memory. When we write new KueUlangTahun(...), the object in the warehouse has two layers:
- The
Kuelayer inside, which holdsrasa. - An extra layer outside, which holds
ucapan.
The parent layer is always built first. That is why super(...) must come at the start of the child's constructor.
5. The "Is A" Test: When to Use Inheritance
There is one simple test. Say it out loud: the child is a parent.
| Sentence | Does it fit? | Use |
|---|---|---|
| A birthday cake is a cake | Yes | extends |
| A manager is an employee | Yes | extends |
| A car is an engine | No. A car has an engine. | A field, for example private Mesin mesin; |
For a "has a" relationship, just use a field. Do not use extends.
One more rule: in Java, a class can have only one direct parent.
6. A Real Example: Employee Pay
A new folder, three files. Karyawan means "employee", manajer means "manager", gaji means "salary" and tunjangan means "allowance".
The file Karyawan.java:
public class Karyawan {
private String nama;
private int gaji;
public Karyawan(String nama, int gaji) {
this.nama = nama;
this.gaji = gaji;
}
public String getNama() {
return nama;
}
public int getGaji() {
return gaji;
}
public int totalGaji() {
return gaji;
}
}
The file Manajer.java:
public class Manajer extends Karyawan {
private int tunjangan;
public Manajer(String nama, int gaji, int tunjangan) {
super(nama, gaji);
this.tunjangan = tunjangan;
}
public int totalGaji() {
return getGaji() + tunjangan;
}
}
The file Main.java:
void main() {
Karyawan rani = new Karyawan("Rani", 6_000_000);
Manajer budi = new Manajer("Budi", 8_000_000, 2_000_000);
IO.println(rani.getNama() + ": " + rani.totalGaji());
IO.println(budi.getNama() + ": " + budi.totalGaji());
}
Rani: 6000000
Budi: 10000000
Budi is a manager with a salary of 8,000,000 rupiah and an allowance of 2,000,000. His total pay is 10,000,000.
Look at getGaji() in Manajer. gaji is a private field of Karyawan, so even the child may not touch it directly. The child uses the counter that the parent provides.
nama and gaji are not written again in Manajer. If Karyawan gets a new field tomorrow, Manajer inherits it too.
7. Three Inheritance Traps
The error messages below come from javac. If you run with java Main.java, the message is the same, but the file name includes its folder.
Trap one: wanting two parents.
public class KueUlangTahun extends Kue, Roti {
KueUlangTahun.java:1: error: '{' expected
public class KueUlangTahun extends Kue, Roti {
^
1 error
Java allows only one direct parent. After extends Kue, javac expects {, not a comma. For extra abilities, Java has interfaces, which we cover in Part 17.
Trap two: forgetting to call super.
public KueUlangTahun(String rasa, String ucapan) {
this.ucapan = ucapan;
}
KueUlangTahun.java:4: error: constructor Kue in class Kue cannot be applied to given types;
public KueUlangTahun(String rasa, String ucapan) {
^
required: String
found: no arguments
reason: actual and formal argument lists differ in length
1 error
If you do not write super(...), Java quietly tries to call the parent's constructor with no ingredients. But Kue only has a constructor that needs a String. Remember trap three in Part 12.
Trap three: the child touches a private field of the parent.
public void tampil() {
IO.println("Kue rasa " + rasa + ", tulisan: " + ucapan);
}
KueUlangTahun.java:10: error: rasa has private access in Kue
IO.println("Kue rasa " + rasa + ", tulisan: " + ucapan);
^
1 error
Inheritance does not open the vault. Use the parent's getter: getRasa().
Summary
- Inheritance creates a child class with
extends. The child inherits the fields and methods of the parent. supercalls the parent's constructor or method. The parent layer is built first.- Use inheritance only for an "is a" relationship. Java allows only one parent.
Challenge
The file A.java:
public class A {
public A() {
IO.println("A");
}
}
The file B.java:
public class B extends A {
public B() {
IO.println("B");
}
}
The file Main.java:
void main() {
new B();
}
What is the output?
- A.
A, thenB - B.
B, thenA - C. Only
B
A hint: remember the order of the layers in section 4. I explain the answer at the start of Part 16.
Conclusion & What's Next
You can now build a new class from a class that already exists. If you remember only one thing, remember the "is a" test. A birthday cake is a cake, so use extends. A car has an engine, so use a field.
In Part 16, the same command can lead to different behaviour. One universal remote control, but every TV responds in its own way. It is called polymorphism.
Before you move on, try to write a class Motor that inherits a class Kendaraan ("vehicle"), and check it with the "is a" sentence.
See you in Part 16. 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.

