-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Adding code for Animals in Chapter 1
- Loading branch information
1 parent
694212d
commit c266a0c
Showing
1 changed file
with
40 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"); | ||
} | ||
} | ||
} |