comp 248 introduction to programming chapter 4 - defining classes part a dr. aiman hanna department...

30
Comp 248 Introduction to Programming Chapter 4 - Defining Classes Part A 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. Copyright © 2007 Pearson Addison-Wesley

Upload: earl-parsons

Post on 26-Dec-2015

215 views

Category:

Documents


0 download

TRANSCRIPT

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

Comp 248 Introduction to Programming Chapter 4 - Defining Classes

Part A

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

All rights reserved

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

Class DefinitionsClass Definitions You have already been using some of the You have already been using some of the

predefined classes, i.e. predefined classes, i.e. StringString and and ScannerScanner classesclasses

You can add/define your own classes to the You can add/define your own classes to the languagelanguage

A class determines: A class determines: 1) 1) Attributes, or Instance VariablesAttributes, or Instance Variables: the types of data that : the types of data that

an object can contain, an object can contain, 2) 2) MethodsMethods: the actions it can perform: the actions it can perform

Once a new class is defined, Once a new class is defined, objectsobjects, or , or instancesinstances, , can be created from this classcan be created from this class

4-2

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

Class DefinitionsClass Definitions

4-3

int x, y;char ch;

Data declarations

Method declarations

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

The The newnew Operator Operator An object of a class is named or declared by a An object of a class is named or declared by a

variable of the class type:variable of the class type: ClassNameClassName objectName;objectName;

The The newnew operator operator mustmust then be used to create the then be used to create the object and associate it with its variable name object and associate it with its variable name (however, some few exceptions do exist): (however, some few exceptions do exist): objectNameobjectName = new ClassName();= new ClassName();

These can be combined as follows:These can be combined as follows: ClassName objectName = new ClassName();ClassName objectName = new ClassName();

Example:Example: Car c1 = new Car(); // Car is the class name andCar c1 = new Car(); // Car is the class name and

// c1 is the object name// c1 is the object name

4-4

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

Instance Variables and Instance Variables and MethodsMethods

Instance variables (attributes) can be defined Instance variables (attributes) can be defined as in the following two examplesas in the following two examples Note the Note the publicpublic modifier (for now): modifier (for now): public int numberOfDoors;public int numberOfDoors; public double Price;public double Price;

In order to refer to a particular instance In order to refer to a particular instance variable, preface it with its object name as variable, preface it with its object name as follows:follows:c1.pricec1.pricec2.pricec2.pricec1.numberOfDoorsc1.numberOfDoors

C1 & c2 are just two objects from the classC1 & c2 are just two objects from the class

4-5

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

Method definitions are divided into two parts: a Method definitions are divided into two parts: a headingheading and a and a method body:method body: public void myMethod()public void myMethod() //// HeadingHeading {{ code to perform some action code to perform some action // Body // Body and/or compute a value and/or compute a value }}

Methods are invoked using the name of the calling Methods are invoked using the name of the calling object and the method name as follows:object and the method name as follows: objName.methodName();objName.methodName();

Example:Example: C1.getNumberOfDoors();C1.getNumberOfDoors();

Invoking a method is equivalent to executing the Invoking a method is equivalent to executing the method bodymethod body

Instance Variables and Instance Variables and MethodsMethods

4-6

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

File Names and File Names and LocationsLocations

Reminder: a Java file must be given Reminder: a Java file must be given the same name as the class it the same name as the class it contains with an added contains with an added .java.java at the at the endend For example, a class named For example, a class named CarCar must must

be in a file named be in a file named Car.javaCar.java

For now, your program and all the For now, your program and all the classes it uses should be in the same classes it uses should be in the same directory or folderdirectory or folder

4-7

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

More About MethodsMore About Methods

There are two kinds of methods:There are two kinds of methods: Methods that compute/perform an Methods that compute/perform an

action then return a valueaction then return a value Methods that compute/perform an Methods that compute/perform an

action then does not return a value action then does not return a value This type of method is called a This type of method is called a voidvoid

method; in other words, it returns method; in other words, it returns voidvoid

Notice that in both cases, the Notice that in both cases, the function do indeed perform an actionfunction do indeed perform an action

4-8Copyright © 2007 Pearson Addison-Wesley. Copyright © 2007 Aiman Hanna. All rights reserved.

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

More About MethodsMore About Methods

A method that returns a value must A method that returns a value must specify the type of that value in its specify the type of that value in its heading:heading:

public typeReturned methodName(paramList)public typeReturned methodName(paramList)

Note:Note: paramListparamList is optionalis optional

Examples:Examples:

public double getPrice();public double getPrice();

public int getNumOfDoors();public int getNumOfDoors();

public void setNumOfDoors(int nd); public void setNumOfDoors(int nd); // nd is just// nd is just

// a name// a name

4-9

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

mainmain is a is a voidvoid Method Method

A program in Java is just a class that has a A program in Java is just a class that has a mainmain method method

When you give a command to run a Java When you give a command to run a Java program, the run-time system invokes the program, the run-time system invokes the method method mainmain

Note that Note that mainmain is a is a voidvoid method, as method, as indicated by its heading:indicated by its heading:public static void main(String[] args)public static void main(String[] args)

4-10

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

returnreturn Statements Statements

The body of both types of methods The body of both types of methods contains a list of declarations and contains a list of declarations and statements enclosed in a pair of bracesstatements enclosed in a pair of braces public <void or typeReturned> myMethod()public <void or typeReturned> myMethod()

{{

declarations Body declarations Body

statements statements

}}

4-11

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

returnreturn Statements Statements The body of a method that returns a The body of a method that returns a

value must also contain one or more value must also contain one or more returnreturn statements statements

A A returnreturn statement specifies the value statement specifies the value returned and ends the method invocation:returned and ends the method invocation:

return Expression;return Expression;

ExpressionExpression can be any expression that can be any expression that evaluates to something of the type returned evaluates to something of the type returned listed in the method headinglisted in the method heading

4-12

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

returnreturn Statements Statements

A A voidvoid method need not contain a method need not contain a returnreturn statement, unless there is a statement, unless there is a situation that requires the method to situation that requires the method to end before all its code is executedend before all its code is executed

In this context, since it does not In this context, since it does not return a value, a return a value, a returnreturn statement is statement is used without an expression:used without an expression: return;return;

4-13

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

Method DefinitionsMethod Definitions An invocation of a method that returns a An invocation of a method that returns a

value can be used as an expression anyplace value can be used as an expression anyplace that a value of the returned type can be used:that a value of the returned type can be used:double pr;double pr;pr = c1.getPrice();pr = c1.getPrice();

An invocation of a An invocation of a voidvoid method is simply a method is simply a statement:statement:objectName.methodName();objectName.methodName();

Examples: Examples: c1.setPrice(20000);c1.setPrice(20000);c1.showModel();c1.showModel();

4-14

VehicleSearch1.java ((MS-Word file))

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

Example: The Vehicle Example: The Vehicle ClassClass

4-15

SeeSee VehicleSearch1.java

v1, v2 & v3 upon v1, v2 & v3 upon creation creation

int numOfDoors;double price;int maxSpeed;

class Vehicle

numOfDoors 4price 10000

maxSpeed 280

numOfDoors 4

v2

price 10000maxSpeed 280

numOfDoors 4

v3

price 10000maxSpeed 280

v1

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

ConstructorsConstructors A A constructorconstructor is a special kind of method that is is a special kind of method that is

designed to initialize the instance variables for designed to initialize the instance variables for an object:an object:public ClassName(anyParameters){code}public ClassName(anyParameters){code}

A constructor must have the same name as the classA constructor must have the same name as the class A constructor has no type returned, not even A constructor has no type returned, not even voidvoid

4-16

VehicleSearch2.java ((MS-Word file))

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

publicpublic and and privateprivate ModifiersModifiers

The modifier The modifier publicpublic means that there are no means that there are no restrictions on where an instance variable or restrictions on where an instance variable or method can be usedmethod can be used

The modifier The modifier privateprivate means that an instance means that an instance variable or method cannot be accessed by name variable or method cannot be accessed by name outside of the classoutside of the class

4-17

VehicleSearch4.java ((MS-Word file))

VehicleSearch3.java ((MS-Word file))

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

Include a No-Argument Include a No-Argument ConstructorConstructor

You should include a You should include a defaultdefault, or , or no-argument no-argument constructor as part of your program. Default constructor as part of your program. Default constructors will be discussed later in full details. constructors will be discussed later in full details.

If you do not include any constructors in your If you do not include any constructors in your class, Java will automatically create a class, Java will automatically create a defaultdefault or or no-argumentno-argument constructor that takes no arguments, constructor that takes no arguments, performs no initializations, but allows the object to performs no initializations, but allows the object to be createdbe created

If you include even one constructor (possibly non-If you include even one constructor (possibly non-default) in your class, Java will not provide this default) in your class, Java will not provide this default constructordefault constructor

4-18

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

Local VariablesLocal Variables

A variable declared within a method A variable declared within a method definition is called a definition is called a local variablelocal variable All variables declared in the All variables declared in the mainmain

method are local variablesmethod are local variables All method parameters are local All method parameters are local

variablesvariables

If two methods each have a local If two methods each have a local variable of the same name, they are variable of the same name, they are still two entirely different variablesstill two entirely different variables

4-19

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

Global VariablesGlobal Variables

Some programming languages Some programming languages include another kind of variable include another kind of variable called a called a globalglobal variable variable

The Java language does The Java language does not not have have global variablesglobal variables

4-20

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

BlocksBlocks A A blockblock is another name for a compound is another name for a compound

statement, that is, a set of Java statements statement, that is, a set of Java statements enclosed in braces,enclosed in braces,{}{}

A variable declared within a block is local A variable declared within a block is local to that block, and cannot be used outside to that block, and cannot be used outside the blockthe block

Once a variable has been declared within Once a variable has been declared within a block, its name cannot be used for a block, its name cannot be used for anything else within the same method anything else within the same method definitiondefinition

4-21

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

Declaring Variables in a Declaring Variables in a forfor StatementStatement

You can declare one or more variables within You can declare one or more variables within the initialization portion of a the initialization portion of a forfor statement statement

A variable so declared will be local to the A variable so declared will be local to the forfor loop, and cannot be used outside of the looploop, and cannot be used outside of the loop

If you need to use such a variable outside of If you need to use such a variable outside of a loop, then declare it outside the loopa loop, then declare it outside the loop

4-22

Statements15.java ((MS-Word file))

Statements14.java ((MS-Word file))

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

Parameters of a Primitive Parameters of a Primitive TypeType

A method can accept no parameters, one A method can accept no parameters, one parameter, or few of them (parameter list)parameter, or few of them (parameter list) These parameter(s) are referred to as These parameter(s) are referred to as formal formal

parametersparameters

public void setVehicleInfo(int nd, double pr, int mxsp)public void setVehicleInfo(int nd, double pr, int mxsp)

When a method is invoked, the appropriate When a method is invoked, the appropriate values must be passed to the method in the values must be passed to the method in the form of form of argumentsarguments, and must be in the right , and must be in the right orderorder These arguments are called These arguments are called actual parametersactual parametersc1.setVehicleInfo(4, 12500.99, 280);c1.setVehicleInfo(4, 12500.99, 280);

4-23

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

Parameters of a Primitive Parameters of a Primitive TypeType The type of each argument must be compatible The type of each argument must be compatible

with the type of the corresponding parameter. The with the type of the corresponding parameter. The following two statements use the method correctlfollowing two statements use the method correctlc1.setVehicleInfo(4, 12500.99, 280);c1.setVehicleInfo(4, 12500.99, 280);

int n = 5, m = 260;int n = 5, m = 260;double p = 19700.95;double p = 19700.95;

c1.setVehicleInfo(n, p, m);c1.setVehicleInfo(n, p, m);

NOTE: In both examples, the value of each NOTE: In both examples, the value of each argument (not the variable name) is the one argument (not the variable name) is the one plugged into the corresponding method parameterplugged into the corresponding method parameter This method of plugging in arguments for formal This method of plugging in arguments for formal

parameters is known as the parameters is known as the call-by-value mechanismcall-by-value mechanism

4-24

MethodParameters1.java ((MS-Word file))

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

Parameters of a Primitive Parameters of a Primitive TypeType

If argument and parameter types do not If argument and parameter types do not match exactly, Java will attempt to make match exactly, Java will attempt to make an automatic type conversionan automatic type conversion

A primitive argument can be automatically A primitive argument can be automatically type cast from any of the following types, to type cast from any of the following types, to any of the types that appear to its right:any of the types that appear to its right:

bytebyteshortshortintintlonglongfloatfloatdoubledouble charchar

4-25

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

Methods That Return a Boolean Methods That Return a Boolean ValueValue

An invocation of a method that An invocation of a method that returns a value of type returns a value of type booleanboolean returns either returns either truetrue or or falsefalse

Therefore, it is common practice to Therefore, it is common practice to use an invocation of such a method to use an invocation of such a method to control statements and loops where a control statements and loops where a Boolean expression is expectedBoolean expression is expected if-elseif-else statements, statements, whilewhile loops, etc. loops, etc.

4-26

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

Comparing Objects of the Same Comparing Objects of the Same Class for EqualityClass for Equality

You cannot use You cannot use ==== to compare objects to compare objects

4-27

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

Instead use methods such as user-Instead use methods such as user-defined defined equals,equals, or or toStringtoString to to compare the objects compare the objects VehicleCompare2.java VehicleCompare2.java (MS-Word file)(MS-Word file)

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

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

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

Accessor and Mutator Accessor and Mutator MethodsMethods

AccessorAccessor methods allow the programmer to methods allow the programmer to obtain the value of an object's instance variablesobtain the value of an object's instance variables The data can be accessed but not changedThe data can be accessed but not changed The name of an accessor method typically The name of an accessor method typically

starts with the word starts with the word getget

MutatorMutator methods allow the programmer to methods allow the programmer to change the value of an object's instance variables change the value of an object's instance variables in a controlled mannerin a controlled manner Incoming data is typically tested and/or filteredIncoming data is typically tested and/or filtered The name of a mutator method typically starts The name of a mutator method typically starts

with the word with the word setset

4-28

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

EncapsulationEncapsulation

4-29

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

A Class Has Access to Private A Class Has Access to Private Members of All Objects of the Members of All Objects of the

ClassClass Within the definition of a class, Within the definition of a class,

private members of private members of anyany object of the object of the class can be accessed, not just class can be accessed, not just private members of the calling objectprivate members of the calling object

For example, see the equals function in For example, see the equals function in VehicleCompare2.javaVehicleCompare2.java

The function has access to the private The function has access to the private date of the passed object, date of the passed object, vecvec

4-30