practice cs
practice cs
You have five minutes to answer the following questions regarding material from the last lecture.
This quiz is not collected and is not graded.
1
2. Draw the UML class diagram for the following class, Mario.
1 public c l a s s Mario {
2 public f i n a l s t a t i c i n t MAX HEALTH = 8 ;
3 private i n t h e a l t h ;
4
5 public Mario ( ) {
6 t h i s . h e a l t h = MAX HEALTH;
7 }
8
9 public boolean isDead ( ) {
10 return t h i s . h e a l t h <= 0 ;
11 }
12
13 public void takeDamage ( i n t dmg) {
14 i f ( isDead ( ) ) {
15 this . health = 0 ;
16 } else {
17 t h i s . h e a l t h −= dmg ;
18 }
19 }
20
21 public void grabCoin ( ) {
22 i f ( h e a l t h >= MAX HEALTH) {
23 h e a l t h = MAX HEALTH;
24 } else {
25 ++h e a l t h ;
26 }
27 }
28 }
3. You have a class House whose sole constructor requires an integer containing the number of
square feet the house has, and a string containing the house’s address. Write a statement
that declares and initializes a House variable, castle, that is to refer to a 1,666 square-foot
house located at 1600 Transylvania Avenue.
2
4. Match each Java term:
• final
• null
• Object
• private
• public
• static
• this
3
5. This equals method for comparing two Marker’s has a syntax error. The compiler is com-
plaining that it cannot find these symbols for other: type, color and inkLevel.
1 @Override
2 public boolean e q u a l s ( Obj ect o t h e r ) {
3 boolean r e s u l t = f a l s e ;
4 i f ( o t h e r instanceof Marker ) {
5 r e s u l t = t h i s . type == o t h e r . type &&
6 t h i s . c o l o r . e q u a l s ( o t h e r . c o l o r ) &&
7 t h i s . i n k L e v e l == o t h e r . i n k L e v e l ;
8 }
9 return r e s u l t ;
10 }
11
12 // . . .
13 Marker m1 = new Marker ( Marker . Type .PERMANENT, ”RED” ) ;
14 Marker m2 = new Marker ( Marker . Type . DRY ERASE, ”RED” ) ;
15 m1 . e q u a l s (m2 ) ; // e x p e c t : f a l s e ;
Since an object of one type can be compared to an object of any other type, other comes
in to the equals method as an Object. The code first checks that other is an instance of
Marker, but it does not cast it into a variable reference of type Marker. Therefore, when
using other it is only aware of the methods that the Object class provides.
The fix is the new line 5 using typecasting. And then the new reference, m, is used on
line 6,7 and 8 in the place of other:
1 @Override
2 public boolean e q u a l s ( Obj ect o t h e r ) {
3 boolean r e s u l t = f a l s e ;
4 i f ( o t h e r instanceof Marker ) {
5 Marker m = ( Marker ) o t h e r ;
6 r e s u l t = t h i s . type == m. type &&
7 t h i s . c o l o r . e q u a l s (m. c o l o r ) &&
8 t h i s . i n k L e v e l == m. i n k L e v e l ;
9 }
10 return r e s u l t ;
11 }