บทนำเรื่อง Method Overriding และ Recursion

Input/Output และ Streams ใน Java

Alex Liu

Software Development Engineer

การกำหนด base class

  • คลาส Animal แทนสัตว์ทั่วไป
    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
Input/Output และ Streams ใน Java

การสืบทอดด้วย 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();
}
  • แสดงผลทีละบรรทัด:
Animal sound
Bark
Input/Output และ Streams ใน Java

การ Override เมธอดใน 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
Input/Output และ Streams ใน Java

ทำความเข้าใจ Recursion

  • เมธอดที่เรียกตัวเองเพื่อแก้ปัญหา
  • ต้องมี base case เพื่อป้องกัน recursion ไม่สิ้นสุด
public class RecursionExample {
    static void countdown(int n) {
        // Base case
        if (n == 0) return; 
        System.out.println(n);
        // Recursive call
        countdown(n - 1); 
    }
}
Input/Output และ Streams ใน Java

ตัวอย่างการใช้งาน Recursion

  • ตัวอย่างการใช้งาน
    public static void main(String[] args) {
      countdown(5);
    }
    
  • การเรียก recursion จะหยุดเมื่อถึง base case คือ 0
    5
    4
    3
    2
    1
    
Input/Output และ Streams ใน Java

สรุป

  • extends เปิดใช้งานการสืบทอด

  • @Override ปรับเปลี่ยนพฤติกรรมที่สืบทอดมา

  • Recursion แบ่งปัญหาออกเป็นขั้นตอนย่อย

    • Base case ป้องกัน recursion ไม่สิ้นสุด
Input/Output และ Streams ใน Java

มาฝึกกันเถอะ!

Input/Output และ Streams ใน Java

Preparing Video For Download...