Java Reference
In-Depth Information
figure 4.49
The classes for
Exercise 4.20
1 public class Class1
2 {
3 public static int x = 5;
4
5 public final String getX( )
6 { return "" + x + 12; }
7 }
8
9 public class Class2
10 {
11 public static void main( String [ ] args )
12 {
13 Class1 obj = new Class1( );
14 System.out.println( obj.getX( ) );
15 }
16 }
In each of the following code fragments, find any errors and any
unnecessary casts.
a. Base [ ] arr = new Base [ 2 ];
arr[ 0 ] = arr[ 1 ] = new Derived( );
4.21
Derived x = (Derived) arr[ 0 ];
Derived y = ( (Derived[])arr )[ 0 ];
b. Derived [ ] arr = new Derived [ 2 ];
arr[ 0 ] = arr[ 1 ] = new Derived( );
Base x = arr[ 0 ];
Base y = ( (Base[])arr )[ 0 ];
c. Base [ ] arr = new Derived [ 2 ];
arr[ 0 ] = arr[ 1 ] = new Derived( );
Derived x = (Derived) arr[ 0 ];
Derived y = ( (Derived[])arr )[ 0 ];
d. Base [ ] arr = new Derived [ 2 ];
arr[ 0 ] = arr[ 1 ] = new Base( );
IN PRACTICE
4.22
Write a generic copy routine that moves elements from one array to
another identically sized and compatible array.
Write generic methods min and max , each of which accepts two param-
eters and returns the smaller and larger, respectively. Then use those
methods on the String type.
4.23
Search WWH ::




Custom Search