Number generators
# Topic
Polymorphism
# Problem
# Number generators
Here's a class hierarchy of magic number generators.
class BaseNumberGenerator {
protected int base;
public BaseNumberGenerator(int base) {
this.base = base;
}
public int generate() {
return base + 11;
}
}
class NumberGenerator extends BaseNumberGenerator {
public NumberGenerator(int base) {
super(base);
}
@Override
public int generate() {
return super.generate() + getNumber();
}
protected int getNumber() {
return this.base - 7;
}
}
class MagicNumberGenerator extends NumberGenerator {
public MagicNumberGenerator(int base) {
super(base);
}
@Override
protected int getNumber() {
return this.base + 7;
}
}
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
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
You have an instance:
BaseNumberGenerator generator = new MagicNumberGenerator(10);
1
Enter the result of invoking generator.generate()
.
Enter a number:
38
1
Correct.
# Hint & Explain
If the subclass has a method which is called, then the program will use it.
编辑 (opens new window)
上次更新: 2022/09/25, 10:41:23