+ All Categories
Home > Documents > Chapter 4: Writing classes

Chapter 4: Writing classes

Date post: 12-Feb-2016
Category:
Upload: marilu
View: 63 times
Download: 0 times
Share this document with a friend
Description:
Chapter 4: Writing classes. Writing classes . We have been using predefined classes Classes developed by SUN From the Java standard class library Used for the particular functionality they provided Example of predefined classes: String class defined in java.lang package - PowerPoint PPT Presentation
Popular Tags:
42
Chapter 4: Writing classes
Transcript
Page 1: Chapter 4:  Writing classes

Chapter 4: Writing classes

Page 2: Chapter 4:  Writing classes

Writing classes We have been using predefined classes

Classes developed by SUN

From the Java standard class library Used for the particular functionality they provided

Example of predefined classes: String class defined in java.lang package

Now, we will learn to write our own classes To define objects

Page 3: Chapter 4:  Writing classes

OutlineAnatomy of a Class

Encapsulation

Anatomy of a Method

Graphical Objects

Graphical User Interfaces

Buttons and Text Fields

Page 4: Chapter 4:  Writing classes

Own classes Although

Existing class libraries provide many useful classes

Still Essence of object oriented programming development

=> design and implement your own classes

Why? In an attempt to suit your specific needs

Page 5: Chapter 4:  Writing classes

OutlineAnatomy of a Class

Encapsulation

Anatomy of a Method

Graphical Objects

Graphical User Interfaces

Buttons and Text Fields

Page 6: Chapter 4:  Writing classes

Relationship between an object and a class Class

Blueprint of an object The blueprint defines the important characteristics of object

Blueprint of a house defines (walls, windows, doors, etc)

Once blueprint created => use it to build objects (houses)

represents the concept of an object Any object created is a realization of the concept

Example String class (concept) =>

String object (specific characters)

Page 7: Chapter 4:  Writing classes

Another example Suppose a class

Called student represents a particular student Student is the general concept of a student

who has (name, address, Major, GPA)

To whom you need (to set address, major, compute GPA)

Every object created => an actual student

In a system that helps manage the business of a university

one student class and 1000s of student objects

Page 8: Chapter 4:  Writing classes

Object An object

has a state defined by the attributes associated with that object

Attributes of student => Student’s name, address, major, etc..

stores the values of attributes for a particular student

whose attributes defined by variables declared within a class

Page 9: Chapter 4:  Writing classes

Object (cont’d) An object

has behaviors defined by the operations associated with that object

Operations of a student => update student’s address, GPA etc

executes the operations defined by the class

whose operations defined by methods declared within a class

Page 10: Chapter 4:  Writing classes

Examples of classes and possible attributes and operations

Class Attributes Operations

Rectangle Length WidthColor

Set lengthSet widthSet color

Flight AirlineFlight number

Origin cityDestination city

Set airlineSet flight number

Set origin citySet destination city

Employee NameDepartment

Salary

Set nameSet departmentCompute bonusCompute taxes

Page 11: Chapter 4:  Writing classes

Classes A class can contain data declarations

And method declarations

int size, weight;char category;

Data declarations

Method declarations

Page 12: Chapter 4:  Writing classes

Classes and objects Consider a six-sided die (singular of dice)

its state can be defined as which face is showing

its primary behaviour is that it can be rolled

We can represent a die in software By designing a class called Die that

models this state and behaviour

This class would serve as the blueprint for a die object

We can then instantiate As many die objects as we need for our program

Page 13: Chapter 4:  Writing classes

Class design For our Die class

We might declare an integer that Represents the current value showing on the face

One of the methods would roll the die by setting that value to a random number

Between one and six

Page 14: Chapter 4:  Writing classes

Classes We’ll want to design the Die class

with other data and methods to make it a versatile and reusable resource

Any given program will not necessarily use all aspects of a given class

See RollingDice.java

See Die.java

Page 15: Chapter 4:  Writing classes

The Die Class The Die class contains two data values

a constant MAX that represents the maximum face value

an integer faceValue that represents the current face value

The roll method uses the random method

of the Math class to determine a new face value

There are also methods to

explicitly set and retrieve the current face value at any time

Page 16: Chapter 4:  Writing classes

Constructors A constructor is a special method

that is used to set up an object when it is initially created

A constructor has the same name as the class

The Die constructor is used to set the initial face value of each new die object to one

Page 17: Chapter 4:  Writing classes

The toString Method All classes that represent objects

should define a toString method

The toString method

returns a character string that

represents the object in some way

It is called automatically when an object is concatenated to a string

or when it is passed to the println method

Page 18: Chapter 4:  Writing classes

Data Scope The scope of data is the area in a program

in which that data can be referenced (used)

Data declared at the class level

can be referenced by all methods in that class

Data declared in a method

can be used only in that method

Data declared within a method is called local data

In the Die class,

the variable result is declared

inside the toString method -- it is local to that method and cannot be referenced anywhere else

Page 19: Chapter 4:  Writing classes

Instance Data The faceValue variable in the Die class

is called instance data because each instance (object) that is created has its own version of it

A class declares the type of the data,

but it does not reserve any memory space for it

Every time a Die object is created,

a new faceValue variable is created as well

The objects of a class share the methods

but each object has its own data space

That's the only way two objects can have different states

Page 20: Chapter 4:  Writing classes

Instance Data We can depict the two Die objects as follows

die1 5faceValue

die2 2faceValue

Each object maintains its own faceValue variable, and thus its own state

Page 21: Chapter 4:  Writing classes

Outline

Anatomy of a Class

Encapsulation

Anatomy of a Method

Page 22: Chapter 4:  Writing classes

Encapsulation We can take one of two views of an object

Internal The details of the variables and methods of the class

That defines it

External The services that an object provides and how

The object interacts with the rest of the system

From the external view, an object an encapsulated entity, providing set of specific services

These services define the interface to the object

Page 23: Chapter 4:  Writing classes

Encapsulation (cont’d) An object

Should be self-governing => data of object modified only by the object itself

The methods of Die class sole responsible

for changing the value of faceValue

We should make it difficult for code outside class To change the value of a variable declared inside class

=> encapsulation

Page 24: Chapter 4:  Writing classes

Encapsulated object

The code using the object Is called client of the object

Should not be allowed to access variables directly

Uses the methods instead to interact with data

Object encapsulation is achieved Using visibility modifiers

Methods

Data

Client

Page 25: Chapter 4:  Writing classes

Visibility modifiers A modifier is a Java reserved word

That specifies the characteristics of a method or data

Controls access to the members of a class

Java has two main visibility modifiers public: members of a class declared as public

Can be referenced anywhere

private: members of a class declared as private Can only be referenced within the class

Page 26: Chapter 4:  Writing classes

Private variables Public variables

Violate encapsulation because They allow the client to reach in and modify values directly

=> variables should not be declared with public visibility => declared as private

Methods that provide object’s services Are declared with public visibility

So that they can be invoked by clients

Page 27: Chapter 4:  Writing classes

Accessors and mutators Data is generally private

=> class provides services to Access data values through accessor methods

Ex: getFaceValue() read only access to a particular value

Modify data values through mutator methods Ex: setFaceValue changes a particular value

These types of methods are sometimes Referred to as “getters” and “setters”

The name of an accessor method take the form getX Where X is the name of value

The name of a mutator method take the form setX

Page 28: Chapter 4:  Writing classes

methods A method

is a group of statements that is given a name

specifies the code executed, when method is called One by one, the statements of that method are executed When done, control returns to the location of the call And execution continues

its header includes The type of return value + method name + (list of parameters)

Page 29: Chapter 4:  Writing classes

method invocations

If called method and calling method Same class => only method name is needed Different class => invoke through the name of other

class

obj.doThis();

main

helpMe();

doThis helpMe

Page 30: Chapter 4:  Writing classes

Method Header A method declaration begins with a method header

char calc (int num1, int num2, String message)

methodname

returntype

parameter list

The parameter list specifies the typeand name of each parameter

The name of a parameter in the methoddeclaration is called a formal parameter

Page 31: Chapter 4:  Writing classes

Method Body The method header is followed by the method body

char calc (int num1, int num2, String message){ int sum = num1 + num2; char result = message.charAt (sum);

return result;}

The return expressionmust be consistent withthe return type

sum and resultare local data

They are created each time the method is called, and are destroyed when it finishes executing

Page 32: Chapter 4:  Writing classes

Return type Return type specified in method header

Primitive type or class name When the method returns a value In this case, the method must have a return statement

Return statement : return + value to be returned

Or, the reserved word “void” When a method does not return any value In this case, the method does not contain a return statement

Control is returned to calling method at the end of the method

Page 33: Chapter 4:  Writing classes

33

The return Statement The return type of a method indicates

the type of value that the method

sends back to the calling location

method returning no value has a void return type

A return statement

specifies the value that will be returned

return expression;

Its expression must conform to the return type

Page 34: Chapter 4:  Writing classes

Return type Return type specified in method header

Primitive type or class name When the method returns a value In this case, the method must have a return statement

Return statement : return + value to be returned

Or, the reserved word “void” When a method does not return any value In this case, the method does not contain a return statement

Control is returned to calling method at the end of the method

Page 35: Chapter 4:  Writing classes

parameters The parameter list in the header of a method

Specifies The types of the values passed to the method

And the names by which the method refer to those values

given in parentheses after the method name

If empty, an empty set of parentheses is used

Page 36: Chapter 4:  Writing classes

Local Data Local variables can be declared inside a method

The parameters of a method

create automatic local variables when method is invoked

When the method finishes,

all local variables are destroyed

Instance variables declared at the class level

exists as long as the object exists

Page 37: Chapter 4:  Writing classes

Bank Account Example Example demonstrates

implementation details of classes and methods

represent bank account by a class named Account

State can include

the account number, the current balance,

and the name of the owner

An account’s behaviors (or services)

include deposits and withdrawals, and adding interest

Page 38: Chapter 4:  Writing classes

Driver Programs A driver program drives

the use of other, more interesting parts of a program

Driver programs are often used

to test other parts of the software

The Transactions class contains a main method

drives the use of the Account class,

exercising its services

See Transactions.java (page 172) See Account.java (page 173)

Page 39: Chapter 4:  Writing classes

Bank Account Exampleacct1 72354acctNumber

102.56balance

name “Ted Murphy”

acct2 69713acctNumber

40.00balance

name “Jane Smith”

Page 40: Chapter 4:  Writing classes

Bank Account Example There are some improvements that can be made to

the Account class

Formal getters and setters could have been defined for all data

The design of some methods could also be more robust, such as verifying that the amount parameter to the withdraw method is positive

Page 41: Chapter 4:  Writing classes

Constructors revisited When we define a class

We usually define a constructor A method that helps setting the class up Often used to initialize variables associated with each object

Constructors differ from regular method The name of constructor is the same as the class

A constructor cannot return a value Does not have a return type A common mistake is to put a void return type on a constructor

Page 42: Chapter 4:  Writing classes

Constructors revisited (cont’d) Constructor

is used to initialize the newly instantiated object

Don’t have to define a constructor for every class

Each class has a default constructor taking no parameters

This default constructor is used if you don’t provide your own

Default constructor has no effect on the newly created object


Recommended