Introduction to Method Overriding and Recursion

Input/Output and Streams in Java

Alex Liu

Software Development Engineer

Defining a base class

  • The Animal class represents a generic 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 and Streams in Java

Understanding inheritance-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();
}
  • Print both sound line by line:
Animal sound
Bark
Input/Output and Streams in Java

Overriding methods in 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 and Streams in Java

Understanding recursion

  • A method calling itself to solve a problem
  • Requires a base case to prevent infinite 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 and Streams in Java

Recursion sample usage

  • Sample usage
    public static void main(String[] args) {
      countdown(5);
    }
    
  • Recursively call stop when it reach the base case which is 0
    5
    4
    3
    2
    1
    
Input/Output and Streams in Java

Summary

  • extends enables inheritance

  • @Override modifies inherited behavior

  • Recursion breaks problems into smaller steps

    • Base case prevents infinite recursion
Input/Output and Streams in Java

Let's practice!

Input/Output and Streams in Java

Preparing Video For Download...