Inheritance: extends, super, and overriding · Pewarisan: extends, super, dan overriding
Inheritance: building on a class
- Inheritance lets one class reuse another class's fields and methods.
- The class you build on is the superclass (parent); the new class is the subclass (child).
- A subclass is-a kind of its superclass: a
Dogis anAnimal.
Pewarisan: membangun di atas kelas
- Pewarisan memungkinkan satu kelas menggunakan ulang field dan method dari kelas lain.
- Kelas yang Anda bangun di atasnya adalah superclass (induk); kelas baru adalah subclass (anak).
- Subclass merupakan jenis dari superclass-nya: sebuah
DogadalahAnimal.
extends and super
- Write
class Dog extends Animalto makeDoga subclass ofAnimal. Dogautomatically gets every public method ofAnimal, likegetName().- The subclass constructor calls the superclass constructor first with
super(...).
extends dan super
- Tulis
class Dog extends Animaluntuk membuatDogsubclass dariAnimal. Dogsecara otomatis menerima semua public method dariAnimal, sepertigetName().- Konstruktor subclass memanggil konstruktor superclass terlebih dahulu dengan
super(...).
public class Main {
public static void main(String[] args) {
Dog d = new Dog("Rex");
System.out.println(d.getName()); // Rex (inherited from Animal)
System.out.println(d.speak()); // Woof (Dog's own version)
}
}
class Animal {
private String name;
public Animal(String name) { this.name = name; }
public String getName() { return this.name; }
public String speak() { return "some sound"; }
}
class Dog extends Animal {
public Dog(String name) {
super(name); // run Animal's constructor
}
public String speak() { // override Animal's speak()
return "Woof";
}
}
Overriding a method
- A subclass can override an inherited method: give it the same signature, a new body.
Dog'sspeak()replacesAnimal'sspeak()forDogobjects.- Methods it does not override (like
getName()) are still inherited unchanged.
Menimpa method
- Subclass dapat menimpa method yang diwarisi: berikan tanda tangan yang sama, body baru.
Dog'sspeak()menggantikanAnimal'sspeak()untuk objekDog.- Method yang tidak ia timpa (seperti
getName()) tetap diwariskan tanpa perubahan.
super.method() — extend, don't replace
- Sometimes you want the parent's work plus a little more.
- Inside an override,
super.describe()runs the superclass version of the method. - Then you add to its result instead of rewriting it from scratch.
super.method() — perluas, jangan ganti
- Terkadang Anda ingin pekerjaan induk ditambah sedikit lagi.
- Di dalam penimpangan,
super.describe()menjalankan versi superclass dari method tersebut. - Kemudian Anda menambahkan ke hasilnya alih-alih menulisnya dari awal.
public class Main {
public static void main(String[] args) {
Bird b = new Bird("Tweety");
System.out.println(b.describe());
// I am an animal named Tweety, and I can fly
}
}
class Animal {
private String name;
public Animal(String name) { this.name = name; }
public String describe() { return "I am an animal named " + this.name; }
}
class Bird extends Animal {
public Bird(String name) { super(name); }
public String describe() {
return super.describe() + ", and I can fly"; // reuse, then add
}
}
is-a: a subclass fits where its superclass is expected
- Because a
Dogis anAnimal, you can writeAnimal a = new Dog("Spot");. - The variable's type is
Animal, but the object is really aDog. - This "is-a" rule is what makes the next lesson — polymorphism — possible.
is-a: subclass pas di mana superclass diharapkan
- Karena
DogadalahAnimal, Anda bisa menulisAnimal a = new Dog("Spot");. - Tipe variabel adalah
Animal, tetapi objek sebenarnya adalahDog. - Aturan "is-a" inilah yang membuat pelajaran berikutnya — polimorfisme — mungkin.
Common mistakes
super(...)must be the first line of a subclass constructor.- Add
@Overrideso the compiler catches a wrong signature.
Kesalahan umum
super(...)harus menjadi baris pertama dari constructor subclass.- Tambahkan
@Overrideagar compiler menangkap tanda tangan yang salah.
Now you try
- Each task gives you a finished
Animalsuperclass. Write or complete the subclass below it. - A hidden Harness builds your object and checks both inherited and new behaviour.
- Press Run to compile, then Check answer. Your code runs on the server, so even the first run is fast.
Sekarang Anda coba
- Setiap tugas memberikan superclass
Animalyang sudah jadi. Tulis atau lengkapi subclass di bawahnya. - Harness tersembunyi membuat objek Anda dan memeriksa perilaku yang diwarisi serta yang baru.
- Tekan Run untuk kompilasi, lalu Check answer. Kode Anda berjalan di server, sehingga bahkan run pertama pun cepat.
Below the finished Animal, write a class Cat that extends Animal. Give it a constructor Cat(String name) that passes the name up with super(name). Add nothing else — Cat should inherit getName() for free. · Di bawah class selesai Animal, buatlah class Cat yang extends Animal. Berikan constructor Cat(String name) yang meneruskan nama ke atas dengan super(name). Tambahkan tidak ada lagi — Cat harus mewarisi getName() secara gratis.
Click Run to see the output here. · Klik Jalankan untuk melihat output di sini.
Complete the class Cow (it already extends Animal). Override speak() so a Cow returns "Moo" instead of the default. getName() must still work (inherited). · Lengkapi class Cow (sudah extends Animal). Override speak() sehingga saat dipanggil pada Cow akan mengembalikan "Moo" alih-alih nilai default. getName() tetap harus berfungsi (warisan).
Click Run to see the output here. · Klik Jalankan untuk melihat output di sini.
Complete the class Fish (it already extends Animal). Override describe() so it returns the Animal description plus ", and I can swim". Reuse the parent's work by calling super.describe() — do not rewrite the whole sentence. · Lengkapi class Fish (sudah extends Animal). Override describe() agar mengembalikan deskripsi Animal ditambah ", and I can swim". Gunakan kembali kerja induk dengan memanggil super.describe() — jangan tulis ulang seluruh kalimat.
Click Run to see the output here. · Klik Jalankan untuk melihat output di sini.