@@ -7,41 +7,58 @@ public static void main(String[] args) {
7
7
var player = new Player ();
8
8
var entity = player .getCollidingEntity ();
9
9
10
- switch (entity ) {
11
- case Player :
12
- player .move ();
13
- entity .move ();
14
- break ;
15
- case Enemy :
16
- player .die ();
17
- break ;
18
- case Object :
19
- object .move ();
20
- break ;
21
- // we dont need to do this (nor ifs) - because we restricted the implementations types (we know them)
22
- // default:
23
- // throw IllegalStateException("Unexpected entity");
10
+ if (entity instanceof Player p ) {
11
+ player .move ();
12
+ p .move ();
13
+ } else if (entity instanceof Enemy e ) {
14
+ player .kill (e );
15
+ } else if (entity instanceof SceneryObject o ) {
16
+ o .move ();
24
17
}
18
+ // we dont need to do this (nor ifs) - because we restricted the implementations types (we know them)
19
+ // else {
20
+ // throw IllegalStateException("Unexpected entity");
21
+ // }
25
22
}
26
23
}
27
24
28
25
/**
29
26
* Sealed types will help us to restrict which types can extend/implement a type.
30
27
* Will allow us to write less verbose polymorphic code.
28
+ *
29
+ * Constraints:
30
+ * - The sealed class and its permitted subclasses must belong to the same module, and, if declared in an unnamed module, the same package.
31
+ * - Every permitted subclass must directly extend the sealed class.
32
+ * - Every permitted subclass must choose a modifier to describe how it continues the sealing initiated by its superclass:
33
+ * - `final`
34
+ * - `sealed`
35
+ * - `non-sealed` (back to a normal class open to extensibility)
31
36
*/
32
- sealed abstract class GameEntity
33
- permits Player , Enemy , Object {}
37
+ sealed abstract class GameEntity permits Player , Enemy , SceneryObject {
38
+ public void move () {
39
+ System .out .println ("Moving" );
40
+ }
41
+
42
+ public void destroy () {
43
+ System .out .println ("Destroying" );
44
+ }
45
+ }
34
46
35
- class Player extends GameEntity {
47
+ final class Player extends GameEntity {
36
48
/**
37
49
* Returns the entity which is colling with the player.
38
50
*/
39
51
public GameEntity getCollidingEntity () {
40
52
// obscure logic
41
53
return new Enemy ();
42
54
}
55
+
56
+ public void kill (GameEntity killedBy ) {
57
+ // obscure death
58
+ System .out .println ("Killing" );
59
+ }
43
60
}
44
61
45
- class Enemy extends GameEntity {}
62
+ final class Enemy extends GameEntity {}
46
63
47
- class Object extends GameEntity {}
64
+ non-sealed class SceneryObject extends GameEntity {}
0 commit comments