-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStackDemo2.java
More file actions
51 lines (45 loc) · 1.5 KB
/
StackDemo2.java
File metadata and controls
51 lines (45 loc) · 1.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
// stack demo with type derivation based on the article from http://www.25hoursaday.com/CsharpVsJava.html#same
import java.util.Stack;
interface Mammal {
// default speak() implementation
default void speak() {
System.out.println("*Generic mammal sound*");
}
}
class Dog implements Mammal {
// Dog provides its own speak() implementation
public void speak() {
System.out.println("Woof! Woof!");
}
}
class Cat implements Mammal {
// Cat provides its own speak() implementation
public void speak() {
System.out.println("Meow! Meow!");
}
}
class MuteKoala implements Mammal {
// mute koala is mute is no speak() implementation :(
}
class StackDemo2 {
// wildcard with upper bound to capture all Mammal-derived stacks
// (keyword 'extends' used for classes and interfaces!)
public static void annoyNeighbors(Stack<? extends Mammal> pets) {
while (!pets.empty()) {
Mammal animal = pets.pop();
animal.speak();
}
}
public static void main(String[] args) {
// stack of different mammals
Stack<Mammal> pets = new Stack<Mammal>();
// add some animals to the stack (both push() and add() allowed)
pets.add(new Dog());
pets.add(new Cat());
pets.add(new MuteKoala());
// make some animal noise!
System.out.println("Your pets are annoying the neighbors:");
annoyNeighbors(pets);
System.out.println("Your neighbors are furious...");
}
}