1CMSC 131 Fall 2007Jan Plane (Adapted from Bonnie Dorr)Lecture 20:InterfacesLast time:1.Explicit array initialization2.Arrays as arguments3.Arrays of objects4.Privacy leaks 5.Array CopyingToday:1.Interfaces2.WrappersCMSC 131 Fall 2007Jan Plane (Adapted from Bonnie Dorr)1Code Re-useMany operations recur in programmingsortingmax / min(These operations may apply to strings, numbers, etc.)Desirable: one implementation!Less codingLess likely to have typosEasier maintenance of codeCMSC 131 Fall 2007Jan Plane (Adapted from Bonnie Dorr)2PolymorphismUsing an interface we can create one variable that can reference objects of different types (i.e. UMStudent variable referencing CSMajor, CEMajor or PsychMajor)This form of “generalization” is called polymorphismHallmark of OO languagesAllows application of same code to objects of different typesPolymorphism: “A variable that takes on many shapes.”Interfaces: one mechanism Java provides for polymorphisma collection of prototypes (method prototypes but no bodies) akaabstract methodsA class C implements an interface I if C provides implementations of all of I’s abstract methods A class implementing an interface can also provide other methods or implement other interfaces2CMSC 131 Fall 2007Jan Plane (Adapted from Bonnie Dorr)3WrappersWe may want to treat primitives as though they were objectsFor example, generic routines (like PsychoAnalyze) can be implemented using interfaces … but they are not usable on primitive typesTo overcome this problem, Java provides wrappers for primitive typesWrappers: classes whose objects contain single values of the “wrapped type”Wrappers also contain other useful conversion operations (to / from String, etc.)Wrappers included in java.lang:ByteShortIntegerLongFloatDoubleCharacterBooleanCMSC 131 Fall 2007Jan Plane (Adapted from Bonnie Dorr)4The Integer WrapperThe documentation is on-line at http://java.sun.com/j2se/1.5.0/docs/api/NotesConstructorsImplements ComparableDocumentation says “Comparable<Integer>”Comparable in Java 5.0 is a interfaceHas compareTo method, etc.CMSC 131 Fall 2007Jan Plane (Adapted from Bonnie Dorr)5In class Demo: Implementing a method using the Integer classCreate objects of type Integer using the constructorcan be based on int type values or variablesCreate an array of Integer type object references and those objects of type Integeruse the API to access information about the data in the Integer
View Full Document