方法重写与递归简介

Java 中的输入/输出与流

Alex Liu

Software Development Engineer

定义基类

  • 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
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
Java 中的输入/输出与流

方法重写(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
Java 中的输入/输出与流

理解递归

  • 方法通过自我调用来解决问题
  • 必须有基例以防无限递归
public class RecursionExample {
    static void countdown(int n) {
        // Base case
        if (n == 0) return; 
        System.out.println(n);
        // Recursive call
        countdown(n - 1); 
    }
}
Java 中的输入/输出与流

递归示例用法

  • 使用示例
    public static void main(String[] args) {
      countdown(5);
    }
    
  • 递归在达到基例0时停止
    5
    4
    3
    2
    1
    
Java 中的输入/输出与流

总结

  • extends 启用继承

  • @Override 修改继承的方法行为

  • Recursion 将问题拆解为更小步骤

    • 基例 防止无限递归
Java 中的输入/输出与流

Let's practice!

Java 中的输入/输出与流

Preparing Video For Download...