Repository navigation
Expand file tree
/
Copy pathRecycleA.java
More file actions
102 lines (97 loc) · 2.47 KB
/
Copy pathRecycleA.java
File metadata and controls
102 lines (97 loc) · 2.47 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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
//: patterns/recyclea/RecycleA.java
// Recycling with RTTI.
package patterns.recyclea;
import java.util.*;
import java.io.*;
abstract class Trash {
private double weight;
Trash(double wt) { weight = wt; }
abstract double value();
double weight() { return weight; }
// Sums the value of Trash in a bin:
static void sumValue(List<Trash> bin) {
Iterator<Trash> e = bin.iterator();
double val = 0.0f;
while(e.hasNext()) {
// One kind of RTTI:
// A dynamically-checked cast
Trash t = e.next();
// Polymorphism in action:
val += t.weight() * t.value();
System.out.println(
"weight of " +
// Using RTTI to get type
// information about the class:
t.getClass().getName() +
" = " + t.weight());
}
System.out.println("Total value = " + val);
}
}
class Aluminum extends Trash {
static double val = 1.67f;
Aluminum(double wt) { super(wt); }
@Override
double value() { return val; }
static void value(double newval) {
val = newval;
}
}
class Paper extends Trash {
static double val = 0.10f;
Paper(double wt) { super(wt); }
@Override
double value() { return val; }
static void value(double newval) {
val = newval;
}
}
class Glass extends Trash {
static double val = 0.23f;
Glass(double wt) { super(wt); }
@Override
double value() { return val; }
static void value(double newval) {
val = newval;
}
}
public class RecycleA {
public static void main(String[] args) {
List<Trash> bin = new ArrayList<>();
// Fill up the Trash bin:
for(int i = 0; i < 30; i++)
switch((int)(Math.random() * 3)) {
case 0 :
bin.add(new
Aluminum(Math.random() * 100));
break;
case 1 :
bin.add(new
Paper(Math.random() * 100));
break;
case 2 :
bin.add(new
Glass(Math.random() * 100));
}
List<Trash>
glassBin = new ArrayList<>(),
paperBin = new ArrayList<>(),
alBin = new ArrayList<>();
Iterator<Trash> sorter = bin.iterator();
// Sort the Trash:
while(sorter.hasNext()) {
Trash t = sorter.next();
// RTTI to show class membership:
if(t instanceof Aluminum)
alBin.add(t);
if(t instanceof Paper)
paperBin.add(t);
if(t instanceof Glass)
glassBin.add(t);
}
Trash.sumValue(alBin);
Trash.sumValue(paperBin);
Trash.sumValue(glassBin);
Trash.sumValue(bin);
}
} ///:~