Skip to content

Commit 40a3130

Browse files
committed
make AboutCasting a bit clearer
1 parent c779ea8 commit 40a3130

1 file changed

Lines changed: 24 additions & 26 deletions

File tree

‎koans/src/beginner/AboutCasting.java‎

Lines changed: 24 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -35,8 +35,24 @@ public void implicitTypecast() {
3535
assertEquals(c, __);
3636
}
3737

38-
class Parent extends Child { public String complain() { return "TPS reports don't even have a cover letter!"; } }
39-
class GrandParent extends Parent { public String complain() { return "Get your feet off the davenport!"; } }
38+
interface Sleepable {
39+
String sleep();
40+
}
41+
class Child implements Sleepable{
42+
public String sleep() {
43+
return "zzzz";
44+
}
45+
}
46+
class Parent extends Child {
47+
public String complain() {
48+
return "TPS reports don't even have a cover letter!";
49+
}
50+
}
51+
class GrandParent extends Parent {
52+
public String complain() {
53+
return "Get your feet off the davenport!";
54+
}
55+
}
4056

4157
@Koan
4258
public void downCastWithInerhitance() {
@@ -58,33 +74,23 @@ public void downCastAndPolymophism() {
5874

5975
@Koan
6076
public void upCastWithInheritance() {
61-
Object grandParent = new GrandParent();
77+
Child grandParent = new GrandParent();
6278
Parent parentReference = (Parent)grandParent; // Why do we need an explicit cast here?
63-
assertEquals(grandParent instanceof Child,__);
64-
assertEquals(parentReference instanceof GrandParent,__);
65-
assertEquals(parentReference instanceof Parent,__);
66-
assertEquals(parentReference instanceof Child,__);
79+
GrandParent grandParentReference = (GrandParent)parentReference; // Or here?
80+
assertEquals(grandParentReference instanceof GrandParent,__);
81+
assertEquals(grandParentReference instanceof Parent,__);
82+
assertEquals(grandParentReference instanceof Child,__);
6783
}
6884

6985
@Koan
7086
public void upCastAndPolymophism() {
71-
Object grandParent = new GrandParent();
87+
Child grandParent = new GrandParent();
7288
Parent parent = (GrandParent)grandParent;
7389
// Think about the result. Did you expect that? Why?
7490
// How is that different from above?
7591
assertEquals(parent.complain(), __);
7692
}
7793

78-
interface Sleepable {
79-
String sleep();
80-
}
81-
82-
class Child implements Sleepable{
83-
public String sleep() {
84-
return "zzzz";
85-
}
86-
}
87-
8894
@Koan
8995
public void classCasting(){
9096
try{
@@ -103,13 +109,5 @@ public void complicatedCast() {
103109
// How can we access the parent's ability to "complain" - if the reference is held as a superclass?
104110
assertEquals(new Parent().complain(), __);
105111
}
106-
107-
@Koan
108-
public void complicatedCastWithInterface() {
109-
Object parent = new Child();
110-
// What do you need to do in order to call "sleep" on the parent?
111-
assertEquals(new Child().sleep(), __);
112-
}
113-
114112

115113
}

0 commit comments

Comments
 (0)