Comp 248 Introduction to Programming Chapter 4 & 5 Defining Classes Part C Dr. Aiman Hanna...

23
Comp 248 Introduction to Programming Chapter 4 & 5 Defining Classes Part C Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal, Canada These slides has been extracted, modified and updated from original slides of Absolute Java 3 rd Edition by Savitch; which has originally been prepared by Rose Williams of Binghamton University. Absolute Java is published by Pearson Education / Addison-Wesley.

Transcript of Comp 248 Introduction to Programming Chapter 4 & 5 Defining Classes Part C Dr. Aiman Hanna...

Page 1: Comp 248 Introduction to Programming Chapter 4 & 5 Defining Classes Part C Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

Comp 248 Introduction to Programming Chapter 4 & 5 Defining Classes

Part C

Dr. Aiman HannaDepartment of Computer Science & Software Engineering

Concordia University, Montreal, Canada

These slides has been extracted, modified and updated from original slides of Absolute Java 3 rd Edition by Savitch; which has originally been prepared by Rose Williams of Binghamton University. Absolute Java is published by

Pearson Education / Addison-Wesley.

Copyright © 2007 Pearson Addison-WesleyCopyright © 2007-2013 Aiman Hanna

All rights reserved

Page 2: Comp 248 Introduction to Programming Chapter 4 & 5 Defining Classes Part C Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

Wrapper ClassesWrapper Classes Wrapper classesWrapper classes provide a class type provide a class type

corresponding to each of the primitive corresponding to each of the primitive typestypes This makes it possible to have class types This makes it possible to have class types

that behave somewhat like primitive typesthat behave somewhat like primitive types The wrapper classes for the primitive types The wrapper classes for the primitive types bytebyte, , shortshort, , longlong,, floatfloat,, doubledouble,, and and charchar are (in order) are (in order) ByteByte,, ShortShort,, LongLong,, FloatFloat,, DoubleDouble,, and and CharacterCharacter

Wrapper classes also contain a number of Wrapper classes also contain a number of useful predefined constants and static useful predefined constants and static methodsmethods

5-2

Page 3: Comp 248 Introduction to Programming Chapter 4 & 5 Defining Classes Part C Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

Wrapper ClassesWrapper Classes BoxingBoxing: the process of going from a value : the process of going from a value

of a primitive type to an object of its of a primitive type to an object of its wrapper classwrapper class To convert a primitive value to an "equivalent" To convert a primitive value to an "equivalent"

class type value, create an object of the class type value, create an object of the corresponding wrapper class using the corresponding wrapper class using the primitive value as an argumentprimitive value as an argument

The new object will contain an instance The new object will contain an instance variable that stores a copy of the primitive variable that stores a copy of the primitive valuevalue

Unlike most other classes, a wrapper class Unlike most other classes, a wrapper class does not have a no-argument constructordoes not have a no-argument constructorInteger integerObject = new Integer(42);Integer integerObject = new Integer(42);

5-3

Page 4: Comp 248 Introduction to Programming Chapter 4 & 5 Defining Classes Part C Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

Wrapper ClassesWrapper Classes

UnboxingUnboxing: the process of going from : the process of going from an object of a wrapper class to the an object of a wrapper class to the corresponding value of a primitive corresponding value of a primitive typetype The methods for converting an object The methods for converting an object

from the wrapper classes from the wrapper classes ByteByte,, ShortShort, , IntegerInteger,, LongLong, , FloatFloat,, DoubleDouble, and , and CharacterCharacter to their corresponding to their corresponding primitive type are (in order) primitive type are (in order) byteValuebyteValue,, shortValueshortValue,, intValueintValue,, longValuelongValue,, floatValuefloatValue,, doubleValuedoubleValue, and , and charValuecharValue

None of these methods take an argumentNone of these methods take an argumentint i = integerObject.intValue();int i = integerObject.intValue();

5-4

Page 5: Comp 248 Introduction to Programming Chapter 4 & 5 Defining Classes Part C Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

Automatic Boxing and Automatic Boxing and UnboxingUnboxing

Starting with version 5.0, Java can automatically Starting with version 5.0, Java can automatically do boxing and unboxingdo boxing and unboxing

Instead of creating a wrapper class object using Instead of creating a wrapper class object using the the newnew operation (as shown before), it can be operation (as shown before), it can be done as an automatic type cast:done as an automatic type cast:Integer integerObject = 42;Integer integerObject = 42;

Instead of having to invoke the appropriate Instead of having to invoke the appropriate method (such as method (such as intValueintValue, , doubleValuedoubleValue, , charValuecharValue, etc.) in order to convert from an , etc.) in order to convert from an object of a wrapper class to a value of its object of a wrapper class to a value of its associated primitive type, the primitive value can associated primitive type, the primitive value can be recovered automaticallybe recovered automaticallyint i = integerObject;int i = integerObject;

5-5

Page 6: Comp 248 Introduction to Programming Chapter 4 & 5 Defining Classes Part C Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

Constants and Static Methods in Constants and Static Methods in Wrapper ClassesWrapper Classes

Wrapper classes include useful constants Wrapper classes include useful constants that provide the largest and smallest that provide the largest and smallest values for any of the primitive number values for any of the primitive number typestypes For example, For example, Integer.MAX_VALUEInteger.MAX_VALUE,, Integer.MIN_VALUEInteger.MIN_VALUE,, DoubleDouble..MAX_VALUEMAX_VALUE, , Double.MIN_VALUEDouble.MIN_VALUE, etc., etc.

The The BooleanBoolean class has names for two class has names for two constants of type constants of type BooleanBoolean Boolean.TRUEBoolean.TRUE and and Boolean.FALSEBoolean.FALSE are the are the

Boolean objects that correspond to the values Boolean objects that correspond to the values truetrue and and falsefalse of the primitive type of the primitive type booleanboolean

5-6

Page 7: Comp 248 Introduction to Programming Chapter 4 & 5 Defining Classes Part C Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

Constants and Static Methods in Constants and Static Methods in Wrapper ClassesWrapper Classes

Wrapper classes have static methods that Wrapper classes have static methods that convert a correctly formed string representation convert a correctly formed string representation of a number to the number of a given typeof a number to the number of a given type The methods The methods Integer.parseIntInteger.parseInt,, Long.parseLongLong.parseLong, , Float.parseFloatFloat.parseFloat, and , and Double.parseDoubleDouble.parseDouble do this do this for the primitive types (in order) for the primitive types (in order) intint,, longlong,, floatfloat, and , and doubledouble

Wrapper classes also have static methods that Wrapper classes also have static methods that convert from a numeric value to a string convert from a numeric value to a string representation of the valuerepresentation of the value For example, the expressionFor example, the expression

Double.toString(123.99);Double.toString(123.99); returns the string value returns the string value "123.99""123.99"

The The CharacterCharacter class contains a number of static class contains a number of static methods that are useful for string processingmethods that are useful for string processing

5-7

Page 8: Comp 248 Introduction to Programming Chapter 4 & 5 Defining Classes Part C Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

Some Methods in the Class Some Methods in the Class CharacterCharacter (Part 1 of 3) (Part 1 of 3)

5-8

Page 9: Comp 248 Introduction to Programming Chapter 4 & 5 Defining Classes Part C Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

Some Methods in the Class Some Methods in the Class CharacterCharacter (Part 2 of 3) (Part 2 of 3)

5-9

Page 10: Comp 248 Introduction to Programming Chapter 4 & 5 Defining Classes Part C Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

Some Methods in the Class Some Methods in the Class CharacterCharacter (Part 3 of 3) (Part 3 of 3)

5-10

Page 11: Comp 248 Introduction to Programming Chapter 4 & 5 Defining Classes Part C Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

Class ParametersClass Parameters

All parameters in Java are All parameters in Java are call-by-valuecall-by-value parametersparameters A parameter is a A parameter is a local variablelocal variable that is set that is set

equal to the value of its argumentequal to the value of its argument Therefore, any change to the value of the Therefore, any change to the value of the

parameter cannot change the value of its parameter cannot change the value of its argumentargument

Class type parameters appear to behave Class type parameters appear to behave differently from primitive type differently from primitive type parametersparameters They appear to behave in a way similar to They appear to behave in a way similar to

parameters in languages that have the parameters in languages that have the call-call-by-referenceby-reference parameter passing mechanism parameter passing mechanism

5-11

Page 12: Comp 248 Introduction to Programming Chapter 4 & 5 Defining Classes Part C Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

Class ParametersClass Parameters

The value plugged into a class type The value plugged into a class type parameter is a reference (memory parameter is a reference (memory address)address) Therefore, the parameter becomes another Therefore, the parameter becomes another

name for the argumentname for the argument Any change made to the object named by the Any change made to the object named by the

parameter (i.e., changes made to the values parameter (i.e., changes made to the values of its instance variables) will be made to the of its instance variables) will be made to the object named by the argument, because they object named by the argument, because they are the same objectare the same object

Note that, because it still is a call-by-value Note that, because it still is a call-by-value parameter, any change made to the class type parameter, any change made to the class type parameter itself (i.e., its address) will not parameter itself (i.e., its address) will not change its argument (the reference or change its argument (the reference or memory address)memory address)

5-12

Page 13: Comp 248 Introduction to Programming Chapter 4 & 5 Defining Classes Part C Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

Parameters of a Class Parameters of a Class TypeType

5-13

Page 14: Comp 248 Introduction to Programming Chapter 4 & 5 Defining Classes Part C Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

The Constant The Constant nullnull nullnull is a special constant that may be assigned is a special constant that may be assigned

to a variable of any class typeto a variable of any class typeYourClass yourObject = null;YourClass yourObject = null;

It is used to indicate that the variable has no It is used to indicate that the variable has no "real value""real value" It is often used in constructors to initialize class type It is often used in constructors to initialize class type

instance variables when there is no obvious object to instance variables when there is no obvious object to useuse

nullnull is not an object: It is, rather, a kind of is not an object: It is, rather, a kind of "placeholder" for a reference that does not name "placeholder" for a reference that does not name any memory locationany memory location Because it is like a memory address, use Because it is like a memory address, use ==== or or !=!=

(instead of (instead of equalsequals) to test if a class variable contains ) to test if a class variable contains nullnullif (yourObject == null) . . .if (yourObject == null) . . .

5-14

Page 15: Comp 248 Introduction to Programming Chapter 4 & 5 Defining Classes Part C Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

Pitfall: Null Pointer Pitfall: Null Pointer ExceptionException

Even though a class variable can be initialized to Even though a class variable can be initialized to nullnull, this does not mean that , this does not mean that nullnull is an object is an object nullnull is only a placeholder for an object is only a placeholder for an object

A method cannot be invoked using a variable that A method cannot be invoked using a variable that is initialized to is initialized to nullnull The calling object that must invoke a method does not The calling object that must invoke a method does not

existexist

Any attempt to do this will result in a "Null Any attempt to do this will result in a "Null Pointer Exception" error messagePointer Exception" error message For example, if the class variable has not been initialized For example, if the class variable has not been initialized

at all (and is not assigned to at all (and is not assigned to nullnull), the results will be the ), the results will be the samesame

5-15

Page 16: Comp 248 Introduction to Programming Chapter 4 & 5 Defining Classes Part C Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

Using and Misusing Using and Misusing ReferencesReferences

When writing a program, it is very When writing a program, it is very important to insure that private instance important to insure that private instance variables remain truly privatevariables remain truly private

For a primitive type instance variable, just For a primitive type instance variable, just adding the adding the privateprivate modifier to its modifier to its declaration should insure that there will declaration should insure that there will be no be no privacy leaksprivacy leaks

For a class type instance variable, For a class type instance variable, however, adding the however, adding the privateprivate modifier modifier alone is not sufficientalone is not sufficient

5-16

Page 17: Comp 248 Introduction to Programming Chapter 4 & 5 Defining Classes Part C Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

Copy Constructor for a Class with Copy Constructor for a Class with Primitive Type Instance VariablesPrimitive Type Instance Variables

public Date(Date aDate)public Date(Date aDate){{ if (aDate == null) //Not a real date.if (aDate == null) //Not a real date. {{ System.out.println("Fatal Error.");System.out.println("Fatal Error."); System.exit(0);System.exit(0); }}

month = aDate.month;month = aDate.month; day = aDate.day;day = aDate.day; year = aDate.year;year = aDate.year;}}

5-17

Page 18: Comp 248 Introduction to Programming Chapter 4 & 5 Defining Classes Part C Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

Copy Constructor for a Class with Copy Constructor for a Class with Class Type Instance VariablesClass Type Instance Variables

public Person(Person original)public Person(Person original){{ if (original == null)if (original == null) {{ System.out.println("Fatal error.");System.out.println("Fatal error."); System.exit(0);System.exit(0); }} name = original.name;name = original.name; born = new Date(original.born);born = new Date(original.born); if (original.died == null)if (original.died == null) died = null;died = null; elseelse died = new Date(original.died);died = new Date(original.died);}}

5-18

Page 19: Comp 248 Introduction to Programming Chapter 4 & 5 Defining Classes Part C Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

Copy Constructor for a Class with Copy Constructor for a Class with Class Type Instance VariablesClass Type Instance Variables

Unlike the Unlike the DateDate class, the class, the PersonPerson class class contains three class type instance variablescontains three class type instance variables

If the If the bornborn and and dieddied class type instance class type instance variables for the new variables for the new PersonPerson object were object were merely copied, then they would simply merely copied, then they would simply rename the rename the bornborn and and dieddied variables from variables from the original the original PersonPerson object object

born = original.born //dangerousborn = original.born //dangerousdied = original.died //dangerousdied = original.died //dangerous

This would This would notnot create an independent copy of create an independent copy of the original objectthe original object

5-19

Page 20: Comp 248 Introduction to Programming Chapter 4 & 5 Defining Classes Part C Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

Pitfall: Privacy LeaksPitfall: Privacy Leaks The previously illustrated examples from the The previously illustrated examples from the PersonPerson class show how an incorrect definition class show how an incorrect definition of a constructor can result in a of a constructor can result in a privacy leakprivacy leak

A similar problem can occur with incorrectly A similar problem can occur with incorrectly defined mutator or accessor methodsdefined mutator or accessor methods For example:For example:

public Date getBirthDate()public Date getBirthDate(){{ return born; //dangerousreturn born; //dangerous}}

Instead of:Instead of:public Date getBirthDate()public Date getBirthDate(){{ return new Date(born); //correctreturn new Date(born); //correct}}

5-20

Page 21: Comp 248 Introduction to Programming Chapter 4 & 5 Defining Classes Part C Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

Mutable and Immutable Mutable and Immutable ClassesClasses

The accessor method The accessor method getNamegetName from the from the PersonPerson class appears to contradict the rules for avoiding class appears to contradict the rules for avoiding privacy leaks:privacy leaks:public String getName()public String getName(){{ return name; //Isn't this dangerous?return name; //Isn't this dangerous?}}

5-21

Page 22: Comp 248 Introduction to Programming Chapter 4 & 5 Defining Classes Part C Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

Mutable and Immutable Mutable and Immutable ClassesClasses

A class that contains no methods (other A class that contains no methods (other than constructors) that change any of the than constructors) that change any of the data in an object of the class is called an data in an object of the class is called an immutable classimmutable class Objects of such a class are called Objects of such a class are called immutable immutable

objectsobjects It is perfectly safe to return a reference to an It is perfectly safe to return a reference to an

immutable object because the object cannot immutable object because the object cannot be changed in any waybe changed in any way

The The StringString class is an immutable class class is an immutable class

5-22

Page 23: Comp 248 Introduction to Programming Chapter 4 & 5 Defining Classes Part C Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.

Mutable and Immutable Mutable and Immutable ClassesClasses

A class that contains public mutator A class that contains public mutator methods or other public methods that can methods or other public methods that can change the data in its objects is called a change the data in its objects is called a mutable classmutable class, and its objects are called , and its objects are called mutable objectsmutable objects Never write a method that returns a mutable Never write a method that returns a mutable

objectobject Instead, use a copy constructor to return a Instead, use a copy constructor to return a

reference to a completely independent copy of reference to a completely independent copy of the mutable objectthe mutable object

5-23