Skip to content

Commit

Permalink
Adding code for Animals in Chapter 1
Browse files Browse the repository at this point in the history
  • Loading branch information
bethrobson committed Jul 14, 2021
1 parent 694212d commit c266a0c
Showing 1 changed file with 40 additions and 0 deletions.
40 changes: 40 additions & 0 deletions src/headfirst/designpatterns/strategy/AnimalTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package headfirst.designpatterns.strategy;

import java.util.ArrayList;

public class AnimalTest {

public static void main(String[] args) {
AnimalTest at = new AnimalTest();
at.makeSomeAnimals();
}
public void makeSomeAnimals() {
Animal dog = new Dog();
Animal cat = new Cat();
// treat dogs and cats as their supertype, Animal
ArrayList<Animal> animals = new ArrayList<Animal>();
animals.add(dog);
animals.add(cat);
animals.forEach(Animal::makeSound); // can call makeSound on any Animal
}

public abstract class Animal {
abstract void makeSound();
}
public class Dog extends Animal {
void makeSound() {
bark();
}
void bark() {
System.out.println("Woof");
}
}
public class Cat extends Animal {
void makeSound() {
meow();
}
void meow() {
System.out.println("Meow");
}
}
}

0 comments on commit c266a0c

Please sign in to comment.