Input/Output and Streams in Java
Alex Liu
Software Development Engineer
Animal
class represents a generic animalclass 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
// 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
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
public class RecursionExample {
static void countdown(int n) {
// Base case
if (n == 0) return;
System.out.println(n);
// Recursive call
countdown(n - 1);
}
}
public static void main(String[] args) {
countdown(5);
}
0
5
4
3
2
1
extends
enables inheritance
@Override
modifies inherited behavior
Recursion
breaks problems into smaller steps
Input/Output and Streams in Java