Giới thiệu ghi đè phương thức và đệ quy

Nhập/Xuất và Streams trong Java

Alex Liu

Software Development Engineer

Định nghĩa lớp cơ sở

  • Lớp Animal biểu diễn một động vật chung
    class Animal {
      void makeSound() {
          System.out.println("Animal sound");
      }
      public static void main(String[] args) {
          Animal a = new Animal();
          a.makeSound(); // Output: Animal sound
      }
    }
    
Animal sound
Nhập/Xuất và Streams trong Java

Hiểu kế thừa - extends

// Use `extends` to create a subclass of `Animal` named `Dog`
class Dog extends Animal {
    void bark() {System.out.println("Bark");}
}
public static void main(String[] args) {
    Dog d = new Dog(); // Create new instance of Dog object which extends Animal
    d.makeSound();
    d.bark();
}
  • In cả hai âm thanh theo từng dòng:
Animal sound
Bark
Nhập/Xuất và Streams trong Java

Ghi đè phương thức trong Java

class Cat extends Animal {
    @Override // Use `@Override` to override the behavior of `.makeSound()`
    void makeSound() {
        System.out.println("Meow");
    }
}
public static void main(String[] args) {
    Cat c = new Cat(); // Create a new instance of Cat object which extends Animal
    c.makeSound(); // Call the overrided method `makeSound()`
}
Meow
Nhập/Xuất và Streams trong Java

Hiểu đệ quy

  • Một phương thức tự gọi để giải quyết vấn đề
  • Cần có trường hợp cơ sở để tránh đệ quy vô hạn
public class RecursionExample {
    static void countdown(int n) {
        // Base case
        if (n == 0) return; 
        System.out.println(n);
        // Recursive call
        countdown(n - 1); 
    }
}
Nhập/Xuất và Streams trong Java

Ví dụ đệ quy

  • Ví dụ sử dụng
    public static void main(String[] args) {
      countdown(5);
    }
    
  • Lời gọi đệ quy dừng khi chạm trường hợp cơ sở0
    5
    4
    3
    2
    1
    
Nhập/Xuất và Streams trong Java

Tóm tắt

  • extends cho phép kế thừa

  • @Override thay đổi hành vi được kế thừa

  • Recursion chia nhỏ bài toán thành các bước

    • Trường hợp cơ sở ngăn đệ quy vô hạn
Nhập/Xuất và Streams trong Java

Ayo berlatih!

Nhập/Xuất và Streams trong Java

Preparing Video For Download...