80 likes | 85 Vues
Lecture 27. Exam outline Boxing of primitive types in Java 1.5 Generic types in Java 1.5. Exam will cover. Polymorphism and dynamic binding: so review Lecture 11 and run the quiz generator for chapter 9
E N D
Lecture 27 • Exam outline • Boxing of primitive types in Java 1.5 • Generic types in Java 1.5
Exam will cover • Polymorphism and dynamic binding: so review Lecture 11 and run the quiz generator for chapter 9 • Interfaces, e.g. Comparable: we reviewed Lecture 17 and 18 and ran the quiz generator for chapter 10 in previous class • Exceptions, including text file I/O: review Lecture 23 on your own (we ran the quiz generator for chapter 17 in previous class) • Recursion: run quiz generator for chapter 19 • Arrays: maybe also run quiz generator for chapter 6
Exam will not cover • GUI methods • Floating point details • Sorting algorithm details • Generic types
boxing: new in Java 1.5 • Integer I = 10; // 10 is “boxed” • Thus conversions between primitive types and wrapper types is automatic when needed
Generic types: new in Java 1.5 • Chapter 21 of comprehensive edition of Liang • Can declare a generic type in a class, interface or method and specify a concrete type when using it
The Comparable Interface in Java 1.5 public interface Comparable<T>{ public int compareTo(T o) } • previously there was no <T> and instead of “T o” it was “Object o” • <T> is a generic type
Implementing “max” in Java 1.5 public class Max{ public static<E extends Comparable<E>>E max(E o1, E o2){ if(o1.compareTo(o2) > 0) return o1; else return o2; } } • Our old version of “max” could fail at run time because the objects are not of the same class, e.g. o1 references a String and o2 references an Integer • This cannot happen with the new version: such an error will get caught at compile time • <E extends Comparable<E>>E both defines a limitation on the class E (it has to implement Comparable<E>) and says the return type is E • the 2 args also need to have the same type E
Implementing Compareable<E> • If we want compiler to catch an error when one of the objects references a Date and the other doesn’t, we have to make Date implement Comparable<Date> • Then the explicit parameter to compareTo must be Date, not Object: this does override the compareTo method of the Object class(?) • Now we no longer need a cast – crucial point, as before the cast could have failed at run time