comp 248 introduction to programming chapter 4 & 5 defining classes part b dr. aiman hanna...

22
Comp 248 Introduction to Programming Chapter 4 & 5 Defining Classes Part B 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.

Upload: posy-hamilton

Post on 13-Dec-2015

220 views

Category:

Documents


3 download

TRANSCRIPT

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

Comp 248 Introduction to Programming Chapter 4 & 5 Defining Classes

Part B

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-2013Aiman Hanna

All rights reserved

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

OverloadingOverloading OverloadingOverloading is when two or more methods is when two or more methods in in

the same classthe same class have the same method name have the same method name

To be valid, any two definitions of the To be valid, any two definitions of the method name must have different method name must have different signaturessignatures A signature consists of the name of a method A signature consists of the name of a method

together with its parameter listtogether with its parameter list Differing signatures must have different numbers Differing signatures must have different numbers

and/or types of parametersand/or types of parameters

4-2

Overloading1.java ((MS-Word file))

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

Overloading and Automatic Type Overloading and Automatic Type ConversionConversion

If Java cannot find a method signature that If Java cannot find a method signature that exactly matches a method invocation, it will exactly matches a method invocation, it will try to use automatic type conversiontry to use automatic type conversion

The interaction of overloading and The interaction of overloading and automatic type conversion can have automatic type conversion can have unintended resultsunintended results

In some cases of overloading, because of In some cases of overloading, because of automatic type conversion, a single method automatic type conversion, a single method invocation can be resolved in multiple waysinvocation can be resolved in multiple ways Ambiguous method invocations will produce an Ambiguous method invocations will produce an

error in Java error in Java

4-3

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

You Can Not Overload Operators in You Can Not Overload Operators in JavaJava

Although many programming Although many programming languages, such as C++, allow you languages, such as C++, allow you to overload operators (+, -, etc.), to overload operators (+, -, etc.), Java does not permit thisJava does not permit this You may only use a method name and You may only use a method name and

ordinary method syntax to carry out the ordinary method syntax to carry out the operations you desire operations you desire

4-4

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

Default Variable Default Variable InitializationsInitializations

Instance class variables are automatically Instance class variables are automatically initialized in Javainitialized in Java booleanboolean types are initialized to types are initialized to falsefalse Other primitives are initialized to the Other primitives are initialized to the zerozero of of

their typetheir type Class types are initialized to Class types are initialized to nullnull

However, it is a better practice to explicitly However, it is a better practice to explicitly initialize instance variables in a constructorinitialize instance variables in a constructor

Note: Local variables are not automatically Note: Local variables are not automatically initializedinitialized

4-5

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

The The thisthis Parameter Parameter

All instance variables are understood to have All instance variables are understood to have <the calling object>.<the calling object>. in front of them in front of them

If an explicit name for the calling object is If an explicit name for the calling object is needed, the keyword needed, the keyword thisthis can be used can be used myInstanceVariablemyInstanceVariable always means and is always always means and is always

interchangeable with interchangeable with this.myInstanceVariablethis.myInstanceVariable

4-6

VehicleCompare5.java ((MS-Word file))

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

The The thisthis Parameter Parameter

thisthis mustmust be used if a parameter or be used if a parameter or other local variable with the same other local variable with the same name is used in the methodname is used in the method

Otherwise, all instances of the variable Otherwise, all instances of the variable name will be interpreted as localname will be interpreted as local

int someVariable = this.someVariableint someVariable = this.someVariable

local instance

4-7

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

Information Hiding and Information Hiding and EncapsulationEncapsulation

Information hidingInformation hiding is the practice of separating is the practice of separating how to use a class from the details of its how to use a class from the details of its implementationimplementation AbstractionAbstraction is another term used to express the concept of is another term used to express the concept of

discarding details in order to avoid information overloaddiscarding details in order to avoid information overload

Encapsulation Encapsulation means that the data and methods of means that the data and methods of a class are combined into a single unit (i.e., a class a class are combined into a single unit (i.e., a class object), which hides the implementation detailsobject), which hides the implementation details Knowing the details is unnecessary because interaction Knowing the details is unnecessary because interaction

with the object occurs via a well-defined and simple with the object occurs via a well-defined and simple interfaceinterface

In Java, hiding details is done by marking them In Java, hiding details is done by marking them privateprivate

4-8

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

Static MethodsStatic Methods Sometimes, it is desired to use a function of a Sometimes, it is desired to use a function of a

class without creating objects from this class. In class without creating objects from this class. In such case, the method can be created as such case, the method can be created as staticstatic

When a static method is defined, the keyword When a static method is defined, the keyword staticstatic is placed in the method header is placed in the method headerpublic static returnedType myMethod(parameters) public static returnedType myMethod(parameters) { . . . }{ . . . }

Static methods are invoked using the class name Static methods are invoked using the class name in place of a calling objectin place of a calling objectmaxMiles = MetricConverter.kmToMile(maxSpeed); maxMiles = MetricConverter.kmToMile(maxSpeed);

5-9

VehicleSearch5.java ((MS-Word file))

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

Pitfall: Invoking a Non-static Pitfall: Invoking a Non-static Method Within a Static MethodMethod Within a Static Method

A static method cannot refer to an instance A static method cannot refer to an instance variable of the class, and it cannot invoke a variable of the class, and it cannot invoke a non-static method of the classnon-static method of the class

A static method has no A static method has no thisthis, so it cannot use , so it cannot use an instance variable or method that has an an instance variable or method that has an implicit or explicit implicit or explicit thisthis for a calling object for a calling object

A static method can invoke another static A static method can invoke another static method, howevermethod, however

5-10

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

Static VariablesStatic Variables A A static variablestatic variable is a variable that belongs to the class is a variable that belongs to the class

as a whole, and not just to one objectas a whole, and not just to one object There is only one copy of a static variable per class, unlike There is only one copy of a static variable per class, unlike

instance variables where each object has its own copyinstance variables where each object has its own copy

All objects of the class can read and change a static All objects of the class can read and change a static variablevariable

Although a static method cannot access an instance Although a static method cannot access an instance variable, a static method can access a static variablevariable, a static method can access a static variable

A static variable is declared like an instance variable, A static variable is declared like an instance variable, with the addition of the modifier with the addition of the modifier staticstatic

private static double bestPrice;private static double bestPrice;

5-11

VehicleCompare6.java (MS-Word file)(MS-Word file)

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

Overloading Overloading Constructors Constructors

Constructors can also be overloaded to Constructors can also be overloaded to provide different object creation options provide different object creation options

4-12

VehicleSearch6.java VehicleSearch6.java (MS-Word file)(MS-Word file)

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

Copy ConstructorsCopy Constructors A A copy constructorcopy constructor is a constructor with a is a constructor with a

single argument of the same type as the classsingle argument of the same type as the class

The copy constructor should create an object The copy constructor should create an object that is a separate, independent object, but that is a separate, independent object, but with the instance variables set so that it is an with the instance variables set so that it is an exact copy of the argument objectexact copy of the argument object

5-13

VehicleSearch7.java VehicleSearch7.java (MS-Word file)(MS-Word file)

VehicleSearch8.java VehicleSearch8.java (MS-Word file)(MS-Word file)

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

The The StringTokenizerStringTokenizer ClassClass

The The StringTokenizerStringTokenizer class is used to class is used to recover the words or recover the words or tokenstokens in a multi- in a multi-word word StringString You can use whitespace characters to separate You can use whitespace characters to separate

each token, or you can specify the characters each token, or you can specify the characters you wish to use as separatorsyou wish to use as separators

In order to use the In order to use the StringTokenizerStringTokenizer class, be class, be sure to include the following at the start of the sure to include the following at the start of the file:file:

import java.util.StringTokenizer;import java.util.StringTokenizer;

4-14

Strings2.java Strings2.java (MS-Word file)(MS-Word file)

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

Some Methods in the Some Methods in the StringTokenizerStringTokenizer Class (Part 1 of 2) Class (Part 1 of 2)

4-15

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

Some Methods in the Some Methods in the StringTokenizerStringTokenizer Class (Part 2 of 2) Class (Part 2 of 2)

4-16

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

The The MathMath Class Class The The MathMath class provides a number of class provides a number of

standard mathematical methodsstandard mathematical methods It is found in the It is found in the java.langjava.lang package, so it package, so it

does not require an does not require an importimport statement statement

All of its methods and data are static, All of its methods and data are static, therefore they are invoked with the class name therefore they are invoked with the class name MathMath instead of a calling object instead of a calling object

The The MathMath class has two predefined constants, class has two predefined constants, EE ((e, e, the base of the natural logarithm system) the base of the natural logarithm system) and and PIPI ( (, 3.1415 . . .), 3.1415 . . .)area = Math.PI * radius * radius;area = Math.PI * radius * radius;

5-17

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

Some Methods in the Class Some Methods in the Class MathMath (Part 1 of 5)(Part 1 of 5)

5-18

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

Some Methods in the Class Some Methods in the Class MathMath (Part 2 of 5)(Part 2 of 5)

5-19

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

Some Methods in the Class Some Methods in the Class MathMath (Part 3 of 5)(Part 3 of 5)

5-20

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

Some Methods in the Class Some Methods in the Class MathMath (Part 4 of 5)(Part 4 of 5)

5-21

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

Some Methods in the Class Some Methods in the Class MathMath (Part 5 of 5)(Part 5 of 5)

5-22