- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStackDemo2.java
More file actions
Latest commit
51 lines (45 loc) · 1.5 KB
/
Copy pathStackDemo2.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
importjava.util.Stack;
interfaceMammal {
// default speak() implementation
defaultvoidspeak() {
System.out.println("*Generic mammal sound*");
}
}
classDogimplementsMammal {
// Dog provides its own speak() implementation
publicvoidspeak() {
System.out.println("Woof! Woof!");
}
}
classCatimplementsMammal {
// Cat provides its own speak() implementation
publicvoidspeak() {
System.out.println("Meow! Meow!");
}
}
classMuteKoalaimplementsMammal {
// mute koala is mute is no speak() implementation :(
}
classStackDemo2 {
// wildcard with upper bound to capture all Mammal-derived stacks
// (keyword 'extends' used for classes and interfaces!)
publicstaticvoidannoyNeighbors(Stack<? extendsMammal> pets) {
while (!pets.empty()) {
Mammalanimal = pets.pop();
animal.speak();
}
}
publicstaticvoidmain(String[] args) {
// stack of different mammals
Stack<Mammal> pets = newStack<Mammal>();
// add some animals to the stack (both push() and add() allowed)
pets.add(newDog());
pets.add(newCat());
pets.add(newMuteKoala());
// make some animal noise!
System.out.println("Your pets are annoying the neighbors:");
annoyNeighbors(pets);
System.out.println("Your neighbors are furious...");
}
}