• No results found

Chapter 5: Enhancing Classes Chapter 5: Enhancing Classes

N/A
N/A
Protected

Academic year: 2021

Share "Chapter 5: Enhancing Classes Chapter 5: Enhancing Classes"

Copied!
34
0
0

Loading.... (view fulltext now)

Full text

(1)

Chapter 5: Enhancing Classes Chapter 5: Enhancing 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)

2

Enhancing Classes Enhancing Classes

We can now explore various aspects of classes and objects We can now explore various aspects of classes and objects in more detail

in more detail

Chapter 5 focuses on: Chapter 5 focuses on:

object references and aliases object references and aliases

passing objects as parameters passing objects as parameters

the static modifier the static modifier

nested classes nested classes

interfaces and polymorphism interfaces and polymorphism

events and listeners events and listeners

animation animation

(3)

3

References References

Recall from Chapter 2 that an object reference holds the Recall from Chapter 2 that an object reference holds the memory address of an object

memory address of an object

Rather than dealing with arbitrary addresses, we often Rather than dealing with arbitrary addresses, we often depict a reference graphically as a “pointer” to an object depict a reference graphically as a “pointer” to an object

ChessPiece bishop1 = new ChessPiece();

bishop1

(4)

4

Assignment Revisited Assignment Revisited

The act of assignment takes a copy of a value and stores it in a The act of assignment takes a copy of a value and stores it in a variable

variable

For primitive types: For primitive types:

num2 = num1;

Before

num1

5

num2

12

After

num1

5

num2

5

(5)

5

Reference Assignment Reference Assignment

For object references, assignment copies the memory For object references, assignment copies the memory location:

location:

bishop2 = bishop1;

Before

bishop1 bishop2

After

bishop1 bishop2

(6)

6

Aliases Aliases

Two or more references that refer to the same object are Two or more references that refer to the same object are called

called aliases aliases of each other of each other

One object (and its data) can be accessed using different One object (and its data) can be accessed using different variables

variables

Aliases can be useful, but should be managed carefully Aliases can be useful, but should be managed carefully

Changing the object’s state (its variables) through one Changing the object’s state (its variables) through one reference changes it for all of its aliases

reference changes it for all of its aliases

(7)

7

Garbage Collection Garbage Collection

When an object no longer has any valid references to it, it When an object no longer has any valid references to it, it can no longer be accessed by the program

can no longer be accessed by the program

It is useless, and therefore called It is useless, and therefore called garbage garbage

Java performs Java performs automatic garbage collection automatic garbage collection periodically, periodically, returning an object's memory to the system for future use returning an object's memory to the system for future use

In other languages, the programmer has the responsibility In other languages, the programmer has the responsibility for performing garbage collection

for performing garbage collection

(8)

Passing Objects to Methods Passing Objects to Methods

Parameters in a Java method are Parameters in a Java method are passed by value passed by value

This means that a copy of the actual parameter (the value This means that a copy of the actual parameter (the value passed in) is stored into the formal parameter (in the

passed in) is stored into the formal parameter (in the method header)

method header)

Passing parameters is essentially an assignment Passing parameters is essentially an assignment

When an object is passed to a method, the actual parameter When an object is passed to a method, the actual parameter and the formal parameter become aliases of each other

and the formal parameter become aliases of each other

(9)

Passing Objects to Methods Passing Objects to Methods

What you do to a parameter inside a method may or may What you do to a parameter inside a method may or may not have a permanent effect (outside the method)

not have a permanent effect (outside the method)

See See ParameterPassing ParameterPassing .java .java (page 226) (page 226)

See See ParameterTester ParameterTester .java .java (page 228) (page 228)

See See Num.java Num.java (page 230) (page 230)

Note the difference between changing the reference and Note the difference between changing the reference and changing the object that the reference points to

changing the object that the reference points to

(10)

10

The static Modifier The static Modifier

In Chapter 2 we discussed static methods (also called class In Chapter 2 we discussed static methods (also called class methods) that can be invoked through the class name rather methods) that can be invoked through the class name rather

than through a particular object than through a particular object

For example, the methods of the For example, the methods of the Math class are static Math class are static

To make a method static, we apply the To make a method static, we apply the static static modifier to modifier to the method definition

the method definition

The The static static modifier can be applied to variables as well modifier can be applied to variables as well

It associates a variable or method with the class rather than It associates a variable or method with the class rather than an object

an object

(11)

11

Static Methods Static Methods

public static int triple (int num) {

int result;

result = num * 3;

return result;

}

class Helper class Helper

Because it is static, the method could be invoked as:

Because it is static, the method could be invoked as:

value = Helper.triple (5);

(12)

12

Static Methods Static Methods

The order of the modifiers can be interchanged, but by The order of the modifiers can be interchanged, but by convention visibility modifiers come first

convention visibility modifiers come first

Recall that the Recall that the main main method is static; it is invoked by the method is static; it is invoked by the system without creating an object

system without creating an object

Static methods cannot reference instance variables, because Static methods cannot reference instance variables, because instance variables don't exist until an object exists

instance variables don't exist until an object exists

However, they can reference static variables or local However, they can reference static variables or local variables

variables

(13)

13

Static Variables Static Variables

Static variables are sometimes called Static variables are sometimes called class variables class variables

Normally, each object has its own data space Normally, each object has its own data space

If a variable is declared as static, only one copy of the If a variable is declared as static, only one copy of the variable exists

variable exists

private static float price;

Memory space for a static variable is created as soon as the Memory space for a static variable is created as soon as the class in which it is declared is loaded

class in which it is declared is loaded

(14)

Static Variables Static Variables

All objects created from the class share access to the static All objects created from the class share access to the static variable

variable

Changing the value of a static variable in one object Changing the value of a static variable in one object changes it for all others

changes it for all others

Static methods and variables often work together Static methods and variables often work together

See See CountInstances CountInstances .java .java (page 233) (page 233)

See MyClass.java (page 234) See MyClass.java (page 234)

(15)

Nested Classes Nested Classes

In addition to a class containing data and methods, it can In addition to a class containing data and methods, it can also contain other classes

also contain other classes

A class declared within another class is called a A class declared within another class is called a nested class nested class

Outer Class

Nested

Class

(16)

Nested Classes Nested Classes

A nested class has access to the variables and methods of A nested class has access to the variables and methods of the outer class, even if they are declared private

the outer class, even if they are declared private

In certain situations this makes the implementation of the In certain situations this makes the implementation of the classes easier because they can easily share information classes easier because they can easily share information

Furthermore, the nested class can be protected by the outer Furthermore, the nested class can be protected by the outer class from external use

class from external use

This is a special relationship and should be used with care This is a special relationship and should be used with care

(17)

Nested Classes Nested Classes

A nested class produces a separate bytecode file A nested class produces a separate bytecode file

If a nested class called Inside is declared in an outer class If a nested class called Inside is declared in an outer class called Outside, two bytecode files will be produced:

called Outside, two bytecode files will be produced:

Outside.class

Outside$Inside.class

Nested classes can be declared as static, in which case they Nested classes can be declared as static, in which case they cannot refer to instance variables or methods

cannot refer to instance variables or methods

A nonstatic nested class is called an A nonstatic nested class is called an inner class inner class

(18)

Interfaces Interfaces

A Java A Java interface interface is a collection of abstract methods and is a collection of abstract methods and constants

constants

An An abstract method abstract method is a method header without a method is a method header without a method body body

An abstract method can be declared using the modifier An abstract method can be declared using the modifier abstract

abstract , but because all methods in an interface are , but because all methods in an interface are abstract, it is usually left off

abstract, it is usually left off

An interface is used to formally define a set of methods that An interface is used to formally define a set of methods that a class will implement

a class will implement

(19)

Interfaces Interfaces

public interface Doable {

public void doThis();

public int doThat();

public void doThis2 (float value, char ch);

public boolean doTheOther (int num);

}

interface is a reserved word interface is a reserved word

None of the methods in an None of the methods in an

interface are given interface are given a definition (body) a definition (body)

A semicolon immediately

A semicolon immediately

follows each method header

follows each method header

(20)

Interfaces Interfaces

An interface cannot be instantiated An interface cannot be instantiated

Methods in an interface have public visibility by default Methods in an interface have public visibility by default

A class formally implements an interface by A class formally implements an interface by

stating so in the class header stating so in the class header

providing implementations for each abstract method in the providing implementations for each abstract method in the interface

interface

If a class asserts that it implements an interface, it must If a class asserts that it implements an interface, it must define all methods in the interface or the compiler will define all methods in the interface or the compiler will

produce errors.

produce errors.

(21)

Interfaces Interfaces

public class CanDo implements Doable {

public void doThis () {

// whatever }

public void doThat () {

// whatever }

// etc.

}

implements is a implements is a reserved word reserved word

Each method listed Each method listed

in Doable is

in Doable is

given a definition

given a definition

(22)

Interfaces Interfaces

A class that implements an interface can implement other A class that implements an interface can implement other methods as well

methods as well

See Speaker.java (page 236) See Speaker.java (page 236)

See Philosopher.java (page 237) See Philosopher.java (page 237)

See Dog.java (page 238) See Dog.java (page 238)

A class can implement multiple interfaces A class can implement multiple interfaces

The interfaces are listed in the implements clause, The interfaces are listed in the implements clause, separated by commas

separated by commas

The class must implement all methods in all interfaces The class must implement all methods in all interfaces listed in the header

listed in the header

(23)

Polymorphism via Interfaces Polymorphism via Interfaces

An interface name can be used as the type of an object An interface name can be used as the type of an object reference variable

reference variable

Doable obj;

The The obj reference can be used to point to any object of any obj reference can be used to point to any object of any class that implements the

class that implements the Doable Doable interface interface

The version of The version of doThis doThis that the following line invokes that the following line invokes depends on the type of object that

depends on the type of object that obj is referring to: obj is referring to:

obj.doThis();

(24)

Polymorphism via Interfaces Polymorphism via Interfaces

That reference is That reference is polymorphic polymorphic , which can be defined as , which can be defined as

"having many forms"

"having many forms"

That line of code might execute different methods at That line of code might execute different methods at different times if the object that

different times if the object that obj obj points to changes points to changes

See Talking.java (page 240) See Talking.java (page 240)

Note that polymorphic references must be resolved at run Note that polymorphic references must be resolved at run time; this is called

time; this is called dynamic binding dynamic binding

Careful use of polymorphic references can lead to elegant, Careful use of polymorphic references can lead to elegant, robust software designs

robust software designs

(25)

Interfaces Interfaces

The Java standard class library contains many interfaces The Java standard class library contains many interfaces that are helpful in certain situations

that are helpful in certain situations

The The Comparable Comparable interface contains an abstract method interface contains an abstract method called

called compareTo compareTo , which is used to compare two objects , which is used to compare two objects

The The String class implements String class implements Comparable Comparable which gives which gives us the ability to put strings in alphabetical order

us the ability to put strings in alphabetical order

The The Iterator Iterator interface contains methods that allow the interface contains methods that allow the user to move through a collection of objects easily

user to move through a collection of objects easily

(26)

Events Events

An An event event is an object that represents some activity to which is an object that represents some activity to which we may want to respond

we may want to respond

For example, we may want our program to perform some For example, we may want our program to perform some action when the following occurs:

action when the following occurs:

the mouse is moved the mouse is moved

a mouse button is clicked a mouse button is clicked

the mouse is dragged the mouse is dragged

a graphical button is clicked a graphical button is clicked

a keyboard key is pressed a keyboard key is pressed

a timer expires a timer expires

Often events correspond to user actions, but not always Often events correspond to user actions, but not always

(27)

Events Events

The Java standard class library contains several classes The Java standard class library contains several classes that represent typical events

that represent typical events

Certain objects, such as an applet or a graphical button, Certain objects, such as an applet or a graphical button, generate (fire) an event when it occurs

generate (fire) an event when it occurs

Other objects, called Other objects, called listeners listeners , respond to events , respond to events

We can write listener objects to do whatever we want when We can write listener objects to do whatever we want when an event occurs

an event occurs

(28)

Events and Listeners Events and Listeners

Generator

This object may This object may generate an event generate an event

Listener

This object waits for and This object waits for and

responds to an event responds to an event

Event

When an event occurs, the generator calls When an event occurs, the generator calls

the appropriate method of the listener,

the appropriate method of the listener,

passing an object that describes the event

passing an object that describes the event

(29)

Listener Interfaces Listener Interfaces

We can create a listener object by writing a class that We can create a listener object by writing a class that implements a particular

implements a particular listener interface listener interface

The Java standard class library contains several interfaces The Java standard class library contains several interfaces that correspond to particular event categories

that correspond to particular event categories

For example, the For example, the MouseListener MouseListener interface contains interface contains methods that correspond to mouse events

methods that correspond to mouse events

After creating the listener, we After creating the listener, we add the listener to the add the listener to the

component that might generate the event to set up a formal component that might generate the event to set up a formal

relationship between the generator and listener

relationship between the generator and listener

(30)

Mouse Events Mouse Events

The following are The following are mouse mouse events events : :

mouse pressed - the mouse button is pressed down mouse pressed - the mouse button is pressed down

mouse released - the mouse button is released mouse released - the mouse button is released

mouse clicked - the mouse button is pressed and released mouse clicked - the mouse button is pressed and released

mouse entered - the mouse pointer is moved over a particular mouse entered - the mouse pointer is moved over a particular component

component

mouse exited mouse exited - the mouse pointer is moved off of a particular - the mouse pointer is moved off of a particular component

component

Any given program can listen for some, none, or all of these Any given program can listen for some, none, or all of these

See Dots.java (page 246) See Dots.java (page 246)

See DotsMouseListener.java (page 248) See DotsMouseListener.java (page 248)

(31)

Mouse Motion Events Mouse Motion Events

The following are called The following are called mouse motion events mouse motion events : :

mouse moved mouse moved - the mouse is moved - the mouse is moved

mouse dragged mouse dragged - the mouse is moved while the mouse button is held - the mouse is moved while the mouse button is held down down

There is a corresponding There is a corresponding MouseMotionListener MouseMotionListener interface

interface

One class can serve as both a generator and a listener One class can serve as both a generator and a listener

One class can serve as a listener for multiple event types One class can serve as a listener for multiple event types

See RubberLines.java (page 249) See RubberLines.java (page 249)

(32)

Key Events Key Events

The following are called The following are called key events key events : :

key pressed key pressed - a keyboard key is pressed down - a keyboard key is pressed down

key released key released - a keyboard key is released - a keyboard key is released

key typed key typed - a keyboard key is pressed and released - a keyboard key is pressed and released

The The KeyListener interface handles key events KeyListener interface handles key events

Listener classes are often implemented as inner classes, Listener classes are often implemented as inner classes, nested within the component that they are listening to nested within the component that they are listening to

See Direction.java (page 253) See Direction.java (page 253)

(33)

Animations Animations

An animation is a constantly changing series of pictures or An animation is a constantly changing series of pictures or images that create the illusion of movement

images that create the illusion of movement

We can create animations in Java by changing a picture We can create animations in Java by changing a picture slightly over time

slightly over time

The speed of a Java animation is usually controlled by a The speed of a Java animation is usually controlled by a Timer

Timer object object

The The Timer Timer class is defined in the class is defined in the javax.swing javax.swing package package

(34)

Animations Animations

A A Timer Timer object generates an object generates an ActionEvent every n ActionEvent every n milliseconds (where n is set by the object creator)

milliseconds (where n is set by the object creator)

The The ActionListener ActionListener interface contains an interface contains an actionPerformed

actionPerformed method method

Whenever the timer expires (generating an Whenever the timer expires (generating an ActionEvent) ActionEvent ) the animation can be updated

the animation can be updated

See Rebound.java (page 258) See Rebound.java (page 258)

References

Related documents

Since the data presented in this report were collected using the Tobii Accuracy and Precision Test method version 3, which is a method where several variables are less controlled, the

Our focus is not on the wider contribution of the humanities and social sciences to the study of mental (ill) health and clinical practice; more narrowly, we seek to show how work

We thus bring the main idea into relation, with the con- temporaneous Trismegistic doctrine of the Master-Mind (i.e., the Spiritual Mind) being the Charioteer, and driving

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

As we have discussed in class, JDBC is a very powerful collection of Java classes and interfaces that allow Java programs to communicate with different database management

The sorghum plots were equipped with Time Domain Reflectometry (TDR) probes to measure A horizon water content and neutron access tubes for measurement of water throughout

Despite the fact that Boruta requires an impractical amount of computation time in its default set-up, using the importance source produced by the Random Ferns algorithm decreased

“Policymakers and health industry stakeholders across the country and across the political spectrum understand the critical role that health IT plays in achieving better