• No results found

Chapter 4: Writing Classes Chapter 4: Writing Classes

N/A
N/A
Protected

Academic year: 2021

Share "Chapter 4: Writing Classes Chapter 4: Writing Classes"

Copied!
35
0
0

Loading.... (view fulltext now)

Full text

(1)

Chapter 4: Writing Classes Chapter 4: Writing Classes

Presentation slides for Presentation slides for

Java Software Solutions Java Software Solutions

Foundations of Program Design Foundations of Program Design

Second Edition Second Edition

by John Lewis and William Loftus by John Lewis and William Loftus

Java Software Solutions is published by Addison-Wesley Java Software Solutions is published by Addison-Wesley

Presentation slides are copyright 2000 by John Lewis and William Loftus. All rights reserved.

Presentation slides are copyright 2000 by John Lewis and William Loftus. All rights reserved.

Instructors using the textbook may use and modify these slides for pedagogical purposes.

Instructors using the textbook may use and modify these slides for pedagogical purposes.

(2)

Writing Classes Writing Classes

We've been using predefined classes. Now we will learn to We've been using predefined classes. Now we will learn to write our own classes to define new objects

write our own classes to define new objects

Chapter 4 focuses on: Chapter 4 focuses on:

class declarations class declarations

method declarations method declarations

instance variables instance variables

encapsulation encapsulation

method overloading method overloading

graphics-based objects graphics-based objects

(3)

Objects Objects

An object has: An object has:

state - descriptive characteristics state - descriptive characteristics

behaviors - what it can do (or be done to it) behaviors - what it can do (or be done to it)

For example, consider a coin that can be flipped so that it's For example, consider a coin that can be flipped so that it's face shows either "heads" or "tails"

face shows either "heads" or "tails"

The state of the coin is its current face (heads or tails) The state of the coin is its current face (heads or tails)

The behavior of the coin is that it can be flipped The behavior of the coin is that it can be flipped

Note that the behavior of the coin might change its state Note that the behavior of the coin might change its state

(4)

Classes Classes

A A class class is a blueprint of an object is a blueprint of an object

It is the model or pattern from which objects are created It is the model or pattern from which objects are created

For example, the For example, the String String class is used to define class is used to define String String objects

objects

Each Each String String object contains specific characters (its state) object contains specific characters (its state)

Each Each String String object can perform services (behaviors) such object can perform services (behaviors) such

as as toUpperCase toUpperCase

(5)

Classes Classes

The The String class was provided for us by the Java String class was provided for us by the Java standard class library

standard class library

But we can also write our own classes that define specific But we can also write our own classes that define specific objects that we need

objects that we need

For example, suppose we wanted to write a program that For example, suppose we wanted to write a program that simulates the flipping of a coin

simulates the flipping of a coin

We could write a We could write a Coin Coin class to represent a coin object class to represent a coin object

(6)

Classes Classes

A class contains data declarations and method declarations A class contains data declarations and method declarations

int x, y;

char ch; Data declarations Data declarations

Method declarations

Method declarations

(7)

Data Scope Data Scope

The The scope scope of data is the area in a program in which that of data is the area in a program in which that data can be used (referenced)

data can be used (referenced)

Data declared at the class level can be used by all methods Data declared at the class level can be used by all methods in that class

in that class

Data declared within a method can only be used in that Data declared within a method can only be used in that method

method

Data declared within a method is called Data declared within a method is called local data local data

(8)

Writing Methods Writing Methods

A A method declaration method declaration specifies the code that will be specifies the code that will be executed when the method is invoked (or called) executed when the method is invoked (or called)

When a method is invoked, the flow of control jumps to the When a method is invoked, the flow of control jumps to the method and executes its code

method and executes its code

When complete, the flow returns to the place where the When complete, the flow returns to the place where the method was called and continues

method was called and continues

The invocation may or may not return a value, depending The invocation may or may not return a value, depending on how the method was defined

on how the method was defined

(9)

myMethod();

myMethod compute

Method Control Flow Method Control Flow

The called method could be within the same class, in which The called method could be within the same class, in which case only the method name is needed

case only the method name is needed

(10)

doIt helpMe

helpMe();

obj.doIt();

main

Method Control Flow Method Control Flow

The called method could be part of another class or object The called method could be part of another class or object

(11)

The Coin Class The Coin Class

In our In our Coin Coin class we could define the following data: class we could define the following data:

face face , an integer that represents the current face , an integer that represents the current face

HEADS HEADS and and TAILS TAILS , integer constants that represent the two , integer constants that represent the two possible states

possible states

We might also define the following methods: We might also define the following methods:

a a Coin constructor, to set up the object Coin constructor, to set up the object

a a flip flip method, to flip the coin method, to flip the coin

a a getFace getFace method, to return the current face method, to return the current face

a a toString method, to return a string description for printing toString method, to return a string description for printing

(12)

The Coin Class The Coin Class

See See CountFlips CountFlips .java .java (page 179) (page 179)

See See Coin.java Coin.java (page 180) (page 180)

Once the Once the Coin Coin class has been defined, we can use it again class has been defined, we can use it again in other programs as needed

in other programs as needed

Note that the Note that the CountFlips CountFlips program did not use the program did not use the toString

toString method method

A program will not necessarily use every service provided A program will not necessarily use every service provided by an object

by an object

(13)

Instance Data Instance Data

The The face face variable in the variable in the Coin Coin class is called class is called instance data instance data because each instance (object) of the

because each instance (object) of the Coin Coin class has its own class has its own

A class declares the type of the data, but it does not reserve A class declares the type of the data, but it does not reserve any memory space for it

any memory space for it

Every time a Every time a Coin Coin object is created, a new object is created, a new face face variable is variable is created as well

created as well

The objects of a class share the method definitions, but they The objects of a class share the method definitions, but they have unique data space

have unique data space

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

(14)

Instance Data Instance Data

See FlipRace.java (page 182) See FlipRace.java (page 182)

face 0

coin1

int face;

class Coin

face 1

coin2

(15)

Encapsulation Encapsulation

You can take one of two views of an object: You can take one of two views of an object:

internal - the structure of its data, the algorithms used by its methods internal - the structure of its data, the algorithms used by its methods

external - the interaction of the object with other objects in the external - the interaction of the object with other objects in the program

program

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

providing a set of specific services

These services define the These services define the interface interface to the object to the object

Recall from Chapter 2 that an object is an Recall from Chapter 2 that an object is an abstraction abstraction , hiding , hiding details from the rest of the system

details from the rest of the system

(16)

Encapsulation Encapsulation

An object should be An object should be self-governing self-governing

Any changes to the object's state (its variables) should be Any changes to the object's state (its variables) should be accomplished by that object's methods

accomplished by that object's methods

We should make it difficult, if not impossible, for one We should make it difficult, if not impossible, for one object to "reach in" and alter another object's state object to "reach in" and alter another object's state

The user, or The user, or client client , of an object can request its services, but , of an object can request its services, but it should not have to be aware of how those services are

it should not have to be aware of how those services are accomplished

accomplished

(17)

Encapsulation Encapsulation

An encapsulated object can be thought of as a An encapsulated object can be thought of as a black box black box

Its inner workings are hidden to the client, which only Its inner workings are hidden to the client, which only invokes the interface methods

invokes the interface methods

Client

Client Methods

Data

(18)

Visibility Modifiers Visibility Modifiers

In Java, we accomplish encapsulation through the In Java, we accomplish encapsulation through the appropriate use of

appropriate use of visibility modifiers visibility modifiers

A A modifier modifier is a Java reserved word that specifies particular is a Java reserved word that specifies particular characteristics of a method or data value

characteristics of a method or data value

We've used the modifier We've used the modifier final to define a constant final to define a constant

Java has three visibility modifiers: Java has three visibility modifiers: public public , , private private , ,

and and protected protected

(19)

Visibility Modifiers Visibility Modifiers

Members of a class that are declared with Members of a class that are declared with public visibility public visibility can be accessed from anywhere

can be accessed from anywhere

Members of a class that are declared with Members of a class that are declared with private visibility private visibility can only be accessed from inside the class

can only be accessed from inside the class

Members declared without a visibility modifier have Members declared without a visibility modifier have default default visibility

visibility and can be accessed by any class in the same and can be accessed by any class in the same package

package

Java modifiers are discussed in detail in Appendix F Java modifiers are discussed in detail in Appendix F

(20)

Visibility Modifiers Visibility Modifiers

As a general rule, no object's data should be declared with As a general rule, no object's data should be declared with public visibility

public visibility

Methods that provide the object's services are usually Methods that provide the object's services are usually

declared with public visibility so that they can be invoked declared with public visibility so that they can be invoked

by clients by clients

Public methods are also called Public methods are also called service methods service methods

A method created simply to assist a service method is called A method created simply to assist a service method is called a a support method support method

Since a support method is not intended to be called by a Since a support method is not intended to be called by a

(21)

Method Declarations Revisited Method Declarations Revisited

A method declaration begins with a A method declaration begins with a method header method header

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

method method

name name return

return type type

parameter list parameter list

The parameter list specifies the type The parameter list specifies the type

and name of each parameter and name of each parameter

The name of a parameter in the method The name of a parameter in the method

declaration is called a

declaration is called a formal argument formal argument

(22)

Method Declarations Method Declarations

The method header is followed by the The method header is followed by the method body method body

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

int sum = num1 + num2;

char result = message.charAt (sum);

return result;

}

The return expression must be The return expression must be consistent with the return type consistent with the return type

sum sum and and result result are local data are local data

They are created each

They are created each

time the method is called,

time the method is called,

(23)

The return Statement The return Statement

The The return type return type of a method indicates the type of value that of a method indicates the type of value that the method sends back to the calling location

the method sends back to the calling location

A method that does not return a value has a A method that does not return a value has a void void return return type type

The The return statement return statement specifies the value that will be specifies the value that will be returned

returned

Its expression must conform to the return type Its expression must conform to the return type

(24)

Parameters Parameters

Each time a method is called, the actual arguments Each time a method is called, the actual arguments in the invocation are copied in the invocation are copied into the formal arguments

into the formal arguments

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

int sum = num1 + num2;

char result = message.charAt (sum);

ch = obj.calc (25, count, "Hello");

(25)

Constructors Revisited Constructors Revisited

Recall that a constructor is a special method that is used to Recall that a constructor is a special method that is used to set up a newly created object

set up a newly created object

When writing a constructor, remember that: When writing a constructor, remember that:

it has the same name as the class it has the same name as the class

it does not return a value it does not return a value

it has no return type, not even it has no return type, not even void void

it often sets the initial values of instance variables it often sets the initial values of instance variables

The programmer does not have to define a constructor for The programmer does not have to define a constructor for a class

a class

(26)

Writing Classes Writing Classes

See BankAccounts.java (page 188) See BankAccounts.java (page 188)

See Account.java (page 189) See Account.java (page 189)

An An aggregate object aggregate object is an object that contains references to is an object that contains references to other objects

other objects

An An Account Account object is an aggregate object because it object is an aggregate object because it contains a reference to a

contains a reference to a String object (that holds the String object (that holds the owner's name)

owner's name)

An aggregate object represents a An aggregate object represents a has-a relationship has-a relationship

A bank account A bank account has a has a name name

(27)

Writing Classes Writing Classes

Sometimes an object has to interact with other objects of Sometimes an object has to interact with other objects of the same type

the same type

For example, we might add two For example, we might add two Rational Rational number objects number objects together as follows:

together as follows:

r3 = r1.add(r2);

One object ( One object ( r1 r1 ) is executing the method and another ( ) is executing the method and another ( r2 r2 ) ) is passed as a parameter

is passed as a parameter

See RationalNumbers.java (page 196) See RationalNumbers.java (page 196)

See Rational.java (page 197) See Rational.java (page 197)

(28)

Overloading Methods Overloading Methods

Method overloading Method overloading is the process of using the same method is the process of using the same method name for multiple methods

name for multiple methods

The The signature signature of each overloaded method must be unique of each overloaded method must be unique

The signature includes the number, type, and order of the The signature includes the number, type, and order of the parameters

parameters

The compiler must be able to determine which version of The compiler must be able to determine which version of

the method is being invoked by analyzing the parameters

the method is being invoked by analyzing the parameters

(29)

Overloading Methods Overloading Methods

float tryMe (int x) {

return x + .375;

}

Version 1 Version 1

float tryMe (int x, float y) {

return x*y;

}

Version 2 Version 2

result = tryMe (25, 4.32) Invocation

Invocation

(30)

Overloaded Methods Overloaded Methods

The The println println method is overloaded: method is overloaded:

println (String s) println (String s)

println (int i) println (int i)

println (double d) println (double d)

etc. etc.

The following lines invoke different versions of the The following lines invoke different versions of the println

println method: method:

(31)

Overloading Methods Overloading Methods

Constructors can be overloaded Constructors can be overloaded

An overloaded constructor provides multiple ways to set up An overloaded constructor provides multiple ways to set up a new object

a new object

See SnakeEyes.java (page 203) See SnakeEyes.java (page 203)

See Die.java (page 204) See Die.java (page 204)

(32)

The StringTokenizer Class The StringTokenizer Class

The next example makes use of the The next example makes use of the StringTokenizer StringTokenizer class, which is defined in the

class, which is defined in the java.util java.util package package

A A StringTokenizer StringTokenizer object separates a string into smaller object separates a string into smaller substrings (tokens)

substrings (tokens)

By default, the tokenizer separates the string at white space By default, the tokenizer separates the string at white space

The The StringTokenizer StringTokenizer constructor takes the original constructor takes the original string to be separated as a parameter

string to be separated as a parameter

(33)

Method Decomposition Method Decomposition

A method should be relatively small, so that it can be A method should be relatively small, so that it can be readily understood as a single entity

readily understood as a single entity

A potentially large method should be decomposed into A potentially large method should be decomposed into several smaller methods as needed for clarity

several smaller methods as needed for clarity

Therefore, a service method of an object may call one or Therefore, a service method of an object may call one or more support methods to accomplish its goal

more support methods to accomplish its goal

See PigLatin.java (page 207) See PigLatin.java (page 207)

See PigLatinTranslator.java (page 208) See PigLatinTranslator.java (page 208)

(34)

Applet Methods Applet Methods

In previous examples we've used the In previous examples we've used the paint method of the paint method of the Applet

Applet class to draw on an applet class to draw on an applet

The The Applet Applet class has several methods that are invoked class has several methods that are invoked automatically at certain points in an applet's life

automatically at certain points in an applet's life

The The init init method, for instance, is executed only once when method, for instance, is executed only once when the applet is initially loaded

the applet is initially loaded

The The Applet Applet class also contains other methods that class also contains other methods that generally assist in applet processing

generally assist in applet processing

(35)

Graphical Objects Graphical Objects

Any object we define by writing a class can have graphical Any object we define by writing a class can have graphical elements

elements

The object must simply obtain a graphics context (a The object must simply obtain a graphics context (a Graphics

Graphics object) in which to draw object) in which to draw

An applet can pass its graphics context to another object An applet can pass its graphics context to another object just as it can any other parameter

just as it can any other parameter

See LineUp.java (page 212) See LineUp.java (page 212)

See StickFigure.java (page 215) See StickFigure.java (page 215)

References

Related documents

Située dans un petit hameau entre le village du Cheronnac et la ville de Rochechouart avec tous ces commerces, cette.

LISC will not process final payment requisitions without certification by LISC’s Construction Monitoring Consultant of completion of the work in accordance with

application, including a description of the harm suffered resulting from the commission of any crime committed within the jurisdiction of the Court, or, in case the victim is

“Student-athletes need an orientation, a set of rules, a handbook detailing requirements for eligibility, rules compliance, university services, athletic department services,

In Spain and Italy, the acquisition of citizenship is a lengthy process, which for non-EU migrants, like Indians, takes 10 years of uninterrupted legal stay in the country and

Berries without lesions harvested from symp- tomatic vines at maturity yielded musts with very similar quality characteristics in both the control and the treated plot at

Temporary access to shop card offer any purchase comcast xfinity free shipping coupon code and your shopping for this website uses cookies and movies and sales and safety.. See if

The contract considered in this paper is the wholesale price contract model, the wholesale price w is determined by the manufacturer and retailer jointly, and under