Upload
anis-ward
View
224
Download
0
Embed Size (px)
Citation preview
Object type and wrapper Object type and wrapper classesclasses
Object methodsObject methods Generic classesGeneric classes Interfaces and iteratorsInterfaces and iterators
Generic ProgrammingGeneric Programming
Data StructuresData Structuresand Other Objectsand Other ObjectsUsing JavaUsing Java
Java’s Object TypeJava’s Object Type
All types (except primitive types) are All types (except primitive types) are Object types.Object types.
Recall use of Object type (clone and equals Recall use of Object type (clone and equals methods)methods)
An Object variable is capable of holding a An Object variable is capable of holding a reference to any kind of object.reference to any kind of object.
Widening ConversionWidening Conversion
An assignment x = y is widening if the data An assignment x = y is widening if the data type of x is capable of referring to a wider type of x is capable of referring to a wider variety of things than the type of y.variety of things than the type of y.
int y = 42;int y = 42;double x;double x;
x = y;x = y;
Widening ConversionWidening Conversion
String s = new String(“Engage!”);String s = new String(“Engage!”);
Object obj;Object obj;
obj = s;obj = s;
““Engage!”Engage!”
String sString s Object objObject obj
Narrowing ConversionsNarrowing Conversions
Narrowing conversions generally require an Narrowing conversions generally require an explicit typecast.explicit typecast.
int x;int x;
double y = 3.14;double y = 3.14;
x = (int) y;x = (int) y;
Narrowing ConversionsNarrowing Conversions
String s = new String(“Engage!”);String s = new String(“Engage!”);
Object obj;Object obj;
obj = s;obj = s;
s = new String(“Make it so.”);s = new String(“Make it so.”);
““Engage!”Engage!”
String sString s Object objObject obj
““Make it so.”Make it so.”
……s = (String) obj;s = (String) obj;
Wrapper ClassesWrapper Classes
Problem: primitive types are not Object Problem: primitive types are not Object types:types: byte, short, int, long, float, double, char, byte, short, int, long, float, double, char,
booleanboolean
Wrapper ClassesWrapper Classes
Solution: create special classes in which Solution: create special classes in which each object holds a primitive type:each object holds a primitive type:
bytebyte
shortshort
intint
longlong
floatfloat
doubledouble
charchar
booleanboolean
ByteByte
ShortShort
IntegerInteger
LongLong
FloatFloat
DoubleDouble
CharacterCharacter
BooleanBoolean
Wrapper ClassesWrapper Classes
Each wrapper class has Each wrapper class has ConstructorConstructor intValue methodintValue method
int i = 42;int i = 42;int j;int j;Integer example;Integer example;example = new Integer(i);example = new Integer(i);j = example.intValue( );j = example.intValue( );
boxingboxing
unboxingunboxing
Autoboxing and Auto-unboxingAutoboxing and Auto-unboxing
int i = 42;int i = 42;
int j;int j;
Integer example;Integer example;
example = i;example = i;
j = example;j = example;
AutoboxingAutoboxing
Auto-unboxingAuto-unboxing
Advantage of WrappersAdvantage of Wrappers
The wrapper object is a full Java object, so The wrapper object is a full Java object, so we can use it in ways that we can’t use the we can use it in ways that we can’t use the primitive types (e.g. for generics, as we will primitive types (e.g. for generics, as we will see).see).
Disadvantage of WrappersDisadvantage of Wrappers
Even simple operations take longer because Even simple operations take longer because of boxing and unboxing:of boxing and unboxing:
Integer x = 5;Integer x = 5;
Integer y = 12;Integer y = 12;
Integer z = x + y;Integer z = x + y;
AutoboxAutobox Auto-unboxAuto-unbox Auto-unboxAuto-unbox
Multi-type operationsMulti-type operations
3 solutions3 solutions
1.1. Overloaded methodsOverloaded methods
2.2. Use Object typeUse Object type
3.3. Use generic typesUse generic types
1. Overloaded Methods1. Overloaded Methods
static Integer middle(Integer[] data) {static Integer middle(Integer[] data) {
if (data.length == 0){if (data.length == 0){
return null;return null;
} else {} else {
return data[data.length/2];return data[data.length/2];
}}
}}
1. Overloaded Methods1. Overloaded Methods
static Character middle(Character[] data) {static Character middle(Character[] data) {
if (data.length == 0){if (data.length == 0){
return null;return null;
} else {} else {
return data[data.length/2];return data[data.length/2];
}}
}}
It does the job, but it’s a lot of work It does the job, but it’s a lot of work creating methods for every possible type:creating methods for every possible type:
i = middle(ia);i = middle(ia);
2. Object Methods2. Object Methods
static Object middle(Object[] data) {static Object middle(Object[] data) {
if (data.length == 0){if (data.length == 0){
return null;return null;
} else {} else {
return data[data.length/2];return data[data.length/2];
}}
}}Also does the job, but the call is awkward, Also does the job, but the call is awkward, and certain type errors can’t be found by and certain type errors can’t be found by the compiler:the compiler:
i = (Integer) middle(ia);i = (Integer) middle(ia);
3. Generic Classes3. Generic Classes
Depends on an unspecified underlying data Depends on an unspecified underlying data type that is eventually identified when the type that is eventually identified when the class is used in an application program.class is used in an application program.
Enhances type checking capabilitiesEnhances type checking capabilities The type used to The type used to instantiateinstantiate the generic the generic
type must be a class (not a primitive type…type must be a class (not a primitive type…for primitives, use wrapper class).for primitives, use wrapper class).
Steps to Convert Collection Class to Generic ClassSteps to Convert Collection Class to Generic Class
1.1. Change the class nameChange the class name If you used type in the name, remove itIf you used type in the name, remove it
2.2. Add <E> to all class references (including Add <E> to all class references (including the class name) within the class itselfthe class name) within the class itself
3.3. Change type of the underlying elementChange type of the underlying element Change to E, which stands for “element”Change to E, which stands for “element”
4.4. Change static methods to generic staticChange static methods to generic static Add <E> after keyword “static”Add <E> after keyword “static”
Steps to Convert Collection Class to Generic ClassSteps to Convert Collection Class to Generic Class
5.5. Take care when creating any new E objectsTake care when creating any new E objects Might need to use Object constructorMight need to use Object constructor
6.6. Modify equality testsModify equality tests Most == or != must be changed to use Most == or != must be changed to use equalsequals
methodmethod
7.7. Deal with null references appropriatelyDeal with null references appropriately
8.8. Set unused reference variables to nullSet unused reference variables to null
9.9. Don’t forget to update documentation!Don’t forget to update documentation!
ExamplesExamples
ArrayBagArrayBag ArrayBag2ArrayBag2 NodeNode
Java InterfacesJava Interfaces
An interface is a formal outline of the available An interface is a formal outline of the available methods for some class. Interfaces form a methods for some class. Interfaces form a contract between the class and the outside contract between the class and the outside world, and this contract is enforced at build world, and this contract is enforced at build time by the compiler. If your class claims to time by the compiler. If your class claims to implement an interface, all methods defined by implement an interface, all methods defined by that interface must appear in its source code that interface must appear in its source code before the class will successfully compile.before the class will successfully compile.
ExampleExample
AudioClip
Writing a Class to Implement an InterfaceWriting a Class to Implement an Interface
1.1. Read interface documentationRead interface documentation
2.2. Tell the compiler you are implementing an Tell the compiler you are implementing an interfaceinterface
public class MP3Player implements AudioClippublic class MP3Player implements AudioClip
3.3. Implement all methods defined in the interfaceImplement all methods defined in the interface
Generic InterfacesGeneric Interfaces
Like any generic class, a generic interface Like any generic class, a generic interface depends on one or more unspecified classes depends on one or more unspecified classes (<E>).(<E>).
E.g. E.g. Iterator<E>
Warning!Warning!
Don’t change a list while an iterator is being Don’t change a list while an iterator is being usedused
ExamplesExamples
ListerLister ListerBadListerBad