CS-140 Fall 2018 Test 2 Version A Nov. 12, 2018 Name: 1. (10 points) For the following, Check T if the statement is true, or F if the statement is false. (a) X T F : A class in Java contains fields, and properties, and always explicitly or implicitly extends exactly one other class, and therefore inherits the fields and public instance methods from the extended class. Typo in this question... should have read A class in Java contains fields and methods... students who question properties get credit for a false response. (b) T X F : A referece variable may be declared with an interface as its type, but must refer to an instance of a real class that implements the interface. The reference variable can be used to invoke all of the methods in the real class. Only interface methods can be directly invoked from a reference variable with an interface type. The reference must be upcast to the actual class in order to reference methods defined in the real class that are not in the interface. (c) X T F : If a child overrides its parent s constructor it can still invoke the parent constructor with the super keyword, but if it does so, then it must invoke the parent constructor first. Technically, you cannot override your parent s constructor... but, by specifying nothing, you do inherit your parent s no-argument creator, so there is a sort of inheritance going on. (d) T X F : A child class can modify the private fields of the class that it extends. A child can only modify public or protected fields - not private fields. (e) X T F : We can think of a child object as having a virtual parent object inside the child object. In memory, a child object contains both the child fields and the parent fields. (f) X T F : In Swing, a GUI is divided into rectangular sets of pixels where each rectangular area is managed by a class that is derived from the JComponent class. (g) X T F : In Java there is no requirement that if two objects have the same hashcode, they will be equal to each other. (h) T X F : The name of an anonymous inner class should start with a capital letter. An anonymous inner class is anonymous... it has no name. (i) X T F : When Java expects a reference to a Comparator object, the compiler allows a lambda expression instead. The lambda expression arguments are the same as the arguments to compareto. (j) X T F : There is no List class in Java, just a List interface, which under the covers is implemented by many different implementations of lists, such as a LinkedList or ArrayList. Page 1 of 10
Answer the following questions by filling in the blanks. 2. (10 points) Given an Account class with fields ownerfirstname, ownerlastname, id, and balance, and a compareto method defined as follows: public int compareto ( Account that ) { i f ( ownerlastname. e q u a l s ( that. ownerlastname ) ) { i f ( ownerfirstname. e q u a l s ( that. ownerfirstname ) ) { return ( id that. id ) ; else { return ownerfirstname. compareto ( t h a t. ownerfirstname ) ; else { return ownerlastname. compareto ( that. ownerlastname ) ; and a tostring method defined as follows: public S t r i n g t o S t r i n g ( ) { return Acct : + id + Owner : + ownerfirstname + + ownerlastname + Balance : + S t r i n g. format ( $%.2 f, balance ) ; If printing out an array of Accounts looks like: Before s o r t : Acct : 1500 Owner : John Smith Balance : $100. 0 0 Acct : 1501 Owner : John Doe Balance : $200. 0 0 Acct : 1502 Owner : Arthur Smith Balance : $300. 0 0 Acct : 1503 Owner : John Smith Balance : $400. 0 0 Acct : 1504 Owner : Jane Doe Balance : $500. 0 0 And that array is an argument of the Arrays.sort method, what will get printed after the sort? After s o r t : Acct : 1504 Owner : Jane Doe Balance : $500. 0 0 Acct : 1501 Owner : John Doe Balance : $200. 0 0 Acct : 1502 Owner : Arthur Smith Balance : $300. 0 0 Acct : 1500 Owner : John Smith Balance : $100. 0 0 Acct : 1503 Owner : John Smith Balance : $400. 0 0 I should have asked if the array is printed after the sort, what will get printed. Need to remember Arrays.sort sorts arrays of Comparable objects by invoking compareto to determine which array element is greater than or less than other array elements, where -1 means less than, 0 means equal, and +1 means greater than. The supplied compareto method sorts on last name alphabetically, then first name, then Account number. 2 points for any answer. 5 points off for realizing a list of accounts print, but not understanding how. 1 point off for each incorrect sort. Page 2 of 10
3. (10 points) For the following questions, refer to the club package defined in Listing 1 on page 7, Listing 2 on page 7, Listing 3 on page 7, and Listing 4 on page 7. (a) What will get printed out to the screen if you run the main method from the ClubTester class in the club package? Rotary is meeting. The president is Jane Goodall 2 points for each line. Why did students think every member s name should appear rather than the club name? (b) What line of code in the club package demonstrates the concept of an interface used as a type, and why? In the ClubTester main method, the line stating Club rotary = new... uses the Club interface as a type. The primary reason to do this is to hide the implementation of the the club from the Tester method. There may be other ways to implement a Club, but the Tester class doesn t care (other than when creating a new instance of Club.) -2 for not specifying why. (c) (5 points (bonus)) The ArrayList toarray method can take a single argument - an array of the same type of elements as in the ArrayList. If the array in that argument is too small to fit all of the elements in the ArrayList, then the toarray method will create a larger array of the same type, and put each element of the ArrayList into this newly created array. Assuming an ArrayListClub has at least one member, will the getmembers method ever return the mems array? Why or why not? The mems array will never be returned because mems is initialized to an empty array (length of zero), which can never be big enough to hold all the elements of members (since there is at least one member). The toarray method will allocate a new array for us, and return that new array. The mems array is supplied as a template to tell toarray what kind of array to create. Page 3 of 10
4. (10 points) Given the Java classes in Listing 12 on page 10, Listing 13 on page 10, Listing 14 on page 10, and Listing 15 on page 10, (a) What will the BirdTester.main method print to the terminal when run? Bird Twitter has son Twitterson Duck Jemimah g o e s Quack and has son dejemimah who g o e s Quack Wren Rene s i n g s tweet t w e e t and has son Reneson whose song i s unknown (b) Notice that the coder tried to do the same thing with a wren, Wren wson = wren.sonof();, that he did with a the duck, Duck dson = duck.sonof();, but when he did so, the compiler complained that there was a type mismatch and that it could not convert a Bird to a Wren. Is this a static or dynamic type checking problem, and why? This is a problem with static type checking, because the sonof method is inherited from the Bird class, and returns a static type of Bird, which cannot be upcast to the static type of wson, which is Wren. (c) Notice that the coder tried to mimic the creation of the dson Duck object by upcasting the return value from wren.sonof() to a Wren rather than a Bird. When he did so, the code compiled, but when he ran the code, he got the run-time error message: Exception in thread main java. lang. ClassCastException : t e s t 2. Bird cannot be c a s t to t e s t 2. Wren. Is this a static or dynamic type checking problem, and why? This is an example of dynamic type checking failure. The dynamic type of the return value of wren.sonof is also Bird, because the sonof method in the Bird class returns the result of new Bird(...). The resulting object is ONLY a Bird object, and not a Bird within a Wren. (There is no song field, and just casting to Wren cannot make the song field value appear.) Sorry... I always mix up upcasting and downcasting. I should have said downcasting from the super-class to the sub-class. To avoid static type-checking, the compiler requires an explicit downcast of the result of sonof to the sub-class, Wren. However, that downcast must be based on the fact that the dynamic type of the result of sonof contains Wren. In fact, the dynamic type of the sonof method is Bird, so downcasting is invalid, as discovered at run-time. (d) In the Duck class, the coder used an @Override keyword to tell the compiler to check to make sure that the sonof method in the Duck class overrides the sonof method in the super-class, Bird. The compiler did not issue any error messages in this case, so the override was succesful, even though the sonof method returns a Bird in the Bird class, and a Duck in the Duck class. What is the relationship between Bird and Duck that makes this acceptable. Since Duck is a sub-type of Bird, in the more recent versions of Java (since Java 1.8), Java allows the use of a sub-type where a super-type is expected, even for the return type of an overriden method. This is very powerful because it allows the overriden method to return the supertype, and can then be used to dispatch methods or access public fields available for the super-type that are not allowed on the sub-type. Remember, if we change the types of the arguments, that creates a totally different method - same name, but different signature, and therefore an independent method. The amazing thing about this example is that we are allowed to change the return type, but still override the existing method! This is only possible because any user expecting the parent type result (as specified in the parent method) can still use the child type returned value BECAUSE sub-types can be used anywhere a super-type is expected. Page 4 of 10
5. (20 points) For the following questions, refer to the numbers package defined in Listing 5 on page 8, Listing 6 on page 8, and Listing 7 on page 8. (a) Which line or lines of code illustrated the concept of recursion in the numbers package? In the Numbers class, the gcd static method is invoked recursively if a is not equal to b. Typo alert... this was once the Numbers package, but now it has been moved into the Test2 pacakge. I should have asked in this problem s Listings on the tear off pages. (b) Will the JUnit test case defined by class NumbersTester pass or fail? If it fails, why does it fail? The JUnit test case will pass. The greatest common divisor of 12 and 33 is 3, and the lambda expression that is the second argument of the assertthrows method will throw an IllegalArgumentException. For the second test, the least commmon multiple of 12 and 33 is 132, and lcm will invoke gcd, which will throw an exception. (c) Identify all instances where the concept of first class functions is used in the test2 package, in the classes defined above. Both invocations of assertthrows in the NumbersTester class use first class functions to specify the invocation of a method which throws an exception. Also the argument to the reduce method invoked by main in the FuncStream class is a first class function - a function passed as an argument. (d) If you run the main method in the FuncReduce class, what will get printed to the screen? lcm of [28, 10, 14] is 140 lcm(28,10) = 280/gcd(28,10) = 280/2 = 140. lcm(140,14)=140*14 / gcd(140,14) = 140*14 / 14 = 140. Page 5 of 10
6. (10 points) The folliowing questions refer to the Java classes in Listing 8 on page 9, Listing 9 on page 9, Listing 10 on page 9, and Listing 11 on page 9. (a) Assuming the state just before the System.out.println statement in the Shapedriver main method, complete the following graphical display of memory: (b) What would get printed if you ran java -cp. test2.shapedriver? [Triangle[ 3 vertices area=6.0 ], Rectangle[ 4 vertices area=15.51 ], Rectangle[ 4 vertices area=2.0 ]] (c) The Shapes class tostring method invokes the getarea method, eve though there is no code for getarea in the Shapes class. Explain why the Java compiler allows the invocation of a method which is not defined, and why at run time, there will always be getarea method available. Since getarea is an abstract method, it forces the Shape class to be abstract, and therefore, no object of class Shape can be instantiated. A concrete child of Shape must implement getarea to be concrete, and a class must be concrete before it can be instantiated. Therefore any instantiated object which is a sub-type of Shape must have an implemented getarea method. Page 6 of 10
Tear-off Pages Listing 1: Person.java package club ; public class Person { S t r i n g name ; public Person ( S t r i n g name) { this. name=name ; package club ; public interface Club { void meet ( ) ; void s e t P r e s i d e n t ( Person person ) ; Person g e t P r e s i d e n t ( ) ; boolean add ( Person person ) ; Person [ ] getmembers ( ) ; Listing 2: Club.java Listing 3: ArrayListClub.java package club ; public class ArrayListClub implements Club { ArrayList<Person> members ; S t r i n g name ; Person p r e s i d e n t ; public ArrayListClub ( S t r i n g name) { this. name=name ; members=new ArrayList<Person >(); public void meet ( ) { System. out. p r i n t l n (name + i s meeting. ) ; public void s e t P r e s i d e n t ( Person person ) { p r e s i d e n t=person ; public Person g e t P r e s i d e n t ( ) { return p r e s i d e n t ; public boolean add ( Person person ) { return members. add ( person ) ; public Person [ ] getmembers ( ) { Person [ ] mems= { ; return members. toarray (mems ) ; Listing 4: ClubTester.java package club ; public class ClubTester { public static void main ( S t r i n g [ ] args ) { Club r o t a r y = new ArrayListClub ( Rotary ) ; r o t a r y. add (new Person ( John Smith ) ) ; r o t a r y. add (new Person ( Mary Black ) ) ; r o t a r y. add (new Person ( Jane Goodall ) ) ; r o t a r y. s e t P r e s i d e n t ( ( r o t a r y. getmembers ( ) ) [ 2 ] ) ; r o t a r y. meet ( ) ; System. out. p r i n t l n ( The p r e s i d e n t i s + r o t a r y. g e t P r e s i d e n t ( ). name ) ; Page 7 of 10
Tear-off Pages Listing 5: Numbers.java public class Numbers { static int gcd ( int a, int b ) { i f ( a<=0 b<=0) throw new IllegalArgumentException ( Arg to gcd must be p o s i t i v e ) ; i f ( a==b ) return a ; i f ( a<b ) return gcd ( a, b a ) ; return gcd ( a b, b ) ; static int lcm ( int a, int b ) { return a b / gcd ( a, b ) ; Listing 6: NumbersTester.java class NumbersTester { @Test void t e s t ( ) { a s s e r t E q u a l s ( 3, Numbers. gcd ( 1 2, 3 3 ) ) ; assertthrows ( IllegalArgumentException. class,() >Numbers. gcd (12, 3)); @Test void t e s t l c m ( ) { a s s e r t E q u a l s (132, Numbers. lcm ( 1 2, 3 3 ) ) ; assertthrows ( IllegalArgumentException. class,() >Numbers. lcm (12, 3)); Listing 7: FuncReduce.java import java. u t i l. Arrays ; import java. u t i l. f u n c t i o n. BiFunction ; public class FuncReduce { static int reduce ( int [ ] array, BiFunction<Integer, Integer, Integer > fn, int i n i t ) { int answer=i n i t ; for ( I n t e g e r elem : array ) answer=fn. apply ( answer, elem ) ; return answer ; public static void main ( S t r i n g [ ] args ) { int [ ] v a l s= { 2 8, 1 0, 1 4 ; System. out. p r i n t l n ( lcm o f + Arrays. t o S t r i n g ( v a l s ) + i s + reduce ( vals, Numbers : : lcm, 1 ) ) ; Page 8 of 10
Tear-off Pages Listing 8: Shape.java public abstract class Shape { private int n ; // Number o f v e r t i c e s public Shape ( int n ) { this. n = n ; public int getn ( ) { return n ; public abstract double getarea ( ) ; public S t r i n g t o S t r i n g ( ) { return g e t C l a s s ( ). getsimplename ( ) + [ + n + v e r t i c e s area= + getarea ( ) + ] ; Listing 9: Triangle.java public class T r i a n g l e extends Shape { private double base ; private double h e i g h t ; public T r i a n g l e ( double base, double height ) { super ( 3 ) ; this. base = base ; this. h e i g h t = h e i g h t ; public double getarea ( ) { return ( base height ) / 2 ; Listing 10: Rectangle.java public class Rectangle extends Shape { private double width ; private double h e i g h t ; public Rectangle ( double width, double height ) { super ( 4 ) ; this. width = width ; this. h e i g h t = h e i g h t ; public double getarea ( ) { return width height ; Listing 11: ShapeDriver.java import java. u t i l. Arrays ; public class ShapeDriver { public static void main ( S t r i n g [ ] args ) { Shape [ ] shapes = { new T riangle ( 3. 0, 4. 0 ), new Rectangle ( 3. 3, 4. 7 ), new Rectangle ( 1. 0, 2. 0 ) ; System. out. p r i n t l n ( Arrays. t o S t r i n g ( shapes ) ) ; Page 9 of 10
Tear-off Pages Listing 12: Bird.java public class Bird { S t r i n g name ; public Bird ( S t r i n g name) { this. name = name ; Bird sonof ( ) { return new Bird (name+ son ) ; Listing 13: Duck.java public c l a s s Duck extends Bird { S t r i n g n o i s e ; public Duck ( S t r i n g name) { super (name ) ; n o i s e= Quack ; @Override Duck sonof ( ) { return new Duck ( de +name ) ; // i t s a French duck! Listing 14: Wren.java public c l a s s Wren extends Bird { S t r i n g song ; public Wren( S t r i n g name) { super (name ) ; song= tweet tweet ; Listing 15: BirdTester.java public class BirdTester { public static void main ( S t r i n g [ ] args ) { Bird bird = new Bird ( Twitter ) ; Duck duck = new Duck ( Jemimah ) ; Wren wren = new Wren( Rene ) ; Bird bson = bird. sonof ( ) ; Duck dson = duck. sonof ( ) ; // Wren wson = (Wren) wren. sonof ( ) ; Bird wson = wren. sonof ( ) ; System. out. p r i n t l n ( Bird + bird. name + has son + bson. name ) ; System. out. p r i n t l n ( Duck + duck. name + goes + duck. n o i s e + and has son + dson. name + who goes + dson. n o i s e ) ; System. out. p r i n t l n ( Wren + wren. name + s i n g s + wren. song + and has son + wson. name + whose song i s unknown ) ; Question: 1 2 3 4 5 6 Total Points: 10 10 10 10 20 10 70 Bonus Points: 0 0 5 0 0 0 5 Page 10 of 10