Prelim 1 Solutions 1. This is an illegal program. The declaration {\tt Puzzle[] ps = new Puzzle[10];} creates an array of size 10 that can hold {\tt Puzzle} objects, but each reference in this array is initialized to null. When the {\tt Move} method is invoked, a null pointer exception will be reported because {\tt ps[0]} is null. 2. This is a legal program. It will print 3 78 After the assignment {\tt B[1] = B[0];}, the sub-arrays {\tt B[1]} and {\tt B[0]} are aliased, so the assignment {\tt B[1][0] = 78;} effectively changes {\tt B[0][0]} as well. 3. (a) Overloading: two methods with the same name in a single class or in a class and one of its subclasses, but which differ in either the number of arguments or the types of the arguments ({\em different} type signatures) (b) Overriding: a method defined in a subclass with the {\em same} name and same type signature as a method in superclass (c) The program will print mello yellow jello mello yellow Since the method {\tt s} in class {\tt A} is private, there is no overriding of this method in class {\tt B}. 4. public int kahuna(int[] A) { if (A == null) //null reference {System.out.println("Null array reference passed to kahuna"); return 0; //should throw an exception } if (A.length == 0) //0 length array {System.out.println("Error: array of 0 size"); return 0; //should really be MAXINT } int ret = A[0]; for (int i = 1; i < A.length; i++) //walk over all elements if (A[i] > ret) ret = A[i]; return ret; } 5. (a) By defining a subclass of an existing class or by implementing an interface. (b) The type of the reference must be a super-type of the type of the object. (c) Any number. Any interface implemented by a class or any superclass of that class is a super-type of that class. (d) You can only change the type of a reference, not the type of an object. (e) You write a ``generic'' procedure that will work with objects of any subtype of the reference type. (f) Dynamic binding of methods: the method to be invoked is determined at runtime by ``looking inside the object'' for a method with the right name and type signature. The compiler cannot tell what that method will be since the type of the object can be any subtype of the type of the reference. (g) Compiler checks that there is a method named do with the right type signature in class/interface foo. (h) At runtime, we look inside object whose name is r for a method with that name and type signature.