Download int

Document related concepts
no text concepts found
Transcript
Chapter 8
Creating and Using Model Classes
Go
Section 1 - The Structure of a Model Class
Go
Section 2 - Details about Objects and Model Classes
Go
Section 3 - The Client - Server Relationship and the Model/View Pattern
Go
Section 4 - More about Model Classes
Go
Go
Section 5 - Inheritance, Superclasses and Subclasses
Go
Section 7 - Activation Records and the Scope and Life Time of Variables
Go
Section 8 - GUI Program Examples: Images, Mouse Operations
Section 6 - More About Methods and Parameters
1
Chapter 8 Objectives
•
Design and implement a simple model class from user
requirements.
•
Organize a program with two files that includes a view class
and a model class.
•
Use visibility modifiers (public and private) to make methods
visible to clients and restrict access to data within a class.
2
Chapter 8 Objectives (cont.)
•
Write appropriate mutator methods, accessor methods, and
constructors for a class.
•
Understand how parameters transmit data to methods.
•
Use global instance variables, local variables, and
parameters appropriately in both model classes and view
classes.
•
Utilize private helper methods in model classes when it is
appropriate.
3
Chapter 8 Vocabulary
Here are some of the terms you will become familiar with in
Chapter 8:
•
Accessor
•
Identity
•
Actual parameter
•
Instantiation
•
Behavior
•
Lifetime
•
Constructor
•
Mutator
•
Encapsulation
•
Scope
•
Formal parameter
•
State
•
Helper method
•
Visibility modifier
4
Section 1
The Structure of a Model Class
5
8.1 Model Classes Define Objects
Programmers write model classes when they want to define a
particular kind of object. Each object of a model class may have
many variables associated with it. As an instance (object of the
model class) is constructed, each one of the instance variables of the
object is given a default value or initialized to some other value.
This actually saves an incredible amount of time, because a
programmer would have to declare all of the variables separately in a
program for what would represent an object and what if you had a
large number of them? It would take an incredible amount of time.
Constructing objects is faster and much more efficient!
6
8.1 Constructors of a Model Class
Just like a cookie cutter can cut out the same kind of cookie
(like a gingerbread man) over and over again, a model class is
a template that can construct the same kind of object over and
over again.
If we cut out gingerbread men with a cookie cutter, we could
give some red eyes and some green eyes, but they would all
have eyes. They would have other characteristics also in
common and they all could be customized to our liking.
In Java, if you use the default constructor of a model class,
then all of the objects have exactly the same characteristics. If
we were making gingerbread men that might be all red eyes
with white frosting for their belts.
However, if we use the initializing constructor of a model class,
then we can initialize the values of the object to what we want!
7
8.1 Instance Variables of a Model Class
The instance variables of an object represent the specific
characteristics that an object has. For an example, a Person
may have a name, age, address, and phone number.
So values for a Person object can be stored in the Person
object’s instance variables.
Instance variables of a model class are always declared as
private. What this means is that other classes in other files
cannot directly access those instance variables. In Java and
other object-oriented languages, we design model classes so
that those value must be accessed indirectly through methods.
These methods are called accessor methods.
8
8.1 Accessor & Mutator Methods
By calling an accessor method, you can obtain the value stored
in an instance variable of the object. So, an accessor method
must be declared as public so other classes in other files can
call the method when needed. This is a safe way of operating,
because an instance variable can’t accidentally be changed if it
is made private. If it was made public, it could be accidentally
changed because we could directly access it.
If an instance variable needs to be changed, then we can
explicitly do that by calling a mutator method. A mutator method
is a safe way to change an instance variable, because we know
we would never want to call the method unless we fully
intended on changing the value of an instance variable.
9
8.1 The Public & Private Visibility Modifiers
In Java and other programming languages, the visibility
modifiers public and private are used to determine what code in
files have access to.
Essentially, public means that methods, variables, and
constants that are declared public can be seen, or are visible,
by the code in other files.
The word private means that methods, variables, and constants
that are declared private CANNOT be seen, or are INVISIBLE,
by the code in other files.
The details of this you will understand the more you work with
classes and understand the principle of information hiding.
10
8.1 The toString Method
The state of an object is the values the instance variables of
the object hold at a certain moment of time. So if we want to
get the state of an object, then we can call the toString method.
The toString method is a method that has a standard method
signature that never changes. This method signature exactly
matches the method signature of the toString method in the
Object class. By writing a toString method with the method
signature:
public String toString ( )
we are overloading the toString method of the Object class.
There are reasons we want to overload this method and you
will understand more about that as we go along.
11
8.1 The Object Class
The Object class is sometimes referred to as the “mother” of all
classes in Java, because all classes descend from it. They
descend from it because a hierarchy exists that has the Object
class automatically at the top of the hierarchy.
Object Class
Person Class
We draw the arrow upward to signify that the Person class
inherits from the Object class. Here, Object is the superclass
and Person is the subclass.
12
8.1 The Structure of a Model Class
Generally, the convention of most programmers is to
place the elements of a model class in the following
order:
Package declarations and Import Statements
Class definition line
Global Private instance variables
Constructor methods
Accessor methods
Mutator methods
toString() method
13
8.1 The Structure of a Class Template
Let’s look at the structure of a model class by
inspecting the elements of the Person class.
This file will be sent you.
Later on, you will learn what chaining is and how
to use the Java reserved word this.
14
Section 2
Details about Objects
and Model Classes
15
8.2 What is an Object?
•
An object is a run-time entity that contains data and
responds to messages.
•
Run-time entity means that …
an object exists only when a program is “running”.
•
More specifically, an object exists only from the time it is
constructed in a method until the method is over or until it is
sent to garbage collection. (Note: if the method stops and
calls another method, then the method is not over. It is just
temporarily suspended so the object is temporarily suspended
unless an alias is passed to the method being called.)
16
8.2 What is a Model Class?
•
A model class is a software package or template that
describes the characteristics of similar objects. We could
also think of it as a “cookie cutter”. Just like a cookie cutter
“stamps out” cookies, a model class “stamps out” objects
because it is a template.
•
Two characteristics of an object are:
1. Data - instance variables that define an object’s data
components, in other words, data is stored in these
variables. We also call instance variables fields.
2.
Behavior - methods that define an object’s behavior
when a message is sent to it to perform an operation.
17
8.2 The Behavior of an Object
We said that methods define an object’s behavior. So you can
think of behavior like this … when an object of a model class
calls a method, we like to say that we are sending a
message to that object. However, when we send an object
a message, we are actually asking it to perform an operation
(some behavior) that uses the data stored in itself … not
some other object. So the object that is being sent the
message is being told “how to behave” or “what to do” based
on the data it contains.
18
8.2 Encapsulation
•
Encapsulation is combining data and behavior into a
single software component called an object.
•
The instance variables of an object hold the data for the
object and those values can change at any instance when
a program is running. The current values of the data of
an object is called the state of the object.
•
We call an object … an instance of a class. Even though
it lasts longer than an instant. It can change instantly
when a method is called.
19
8.2 What is Instantiation?
•
Instantiation is the process of creating a new object through
constructing it. An instantiated object of a class is referred to
as an instance of the class. We can create many instances of
a class during a program. Each instance exists as long as the
part of the program that created it and is using it is running.
20
8.2 Some Classes are NOT Model Classes
Some classes are not model classes, but rather driver programs.
You’ve learned that you can have console programs with a
main() method or they may be applets programs like Rocket.
These programs don’t “stamp out” any objects. They are not
templates for creating objects. However, technically in Java,
they create one object and that is the object that is the
program itself, but again, they are not really a template for
creating numerous objects. We sometimes call these driver
programs view files or client files.
21
8.2 Model & Driver Classes
Person Model Class
PersonDriver Class
with
with main method
Constructors
Calls Constructors
Accessors
Calls Accessors
Mutators
Calls Mutators
& toString
& Calls toString
Methods
Methods
defines a Person object
uses Person objects
22
8.2 How a Program maintains Objects
When a Java program begins to run, RAM memory is allocated
to hold:
•
All class templates - the compiled code of all model classes
being used so that objects can be instantiated when needed.
•
Space for variables and objects in any program file, in particular,
for a driver file where objects are generally constructed.
(Memory for instance variables of an object are allocated within
the overall memory allocated for the object.)
Summarizing … instances of a class (objects) appear and
occupy memory when instantiated. Instances disappear when
they are no longer needed ... meaning the memory is freed up
through garbage collection so that it can be reused. All RAM
memory used by a program is freed up when it stops running.
23
8.2 The Identity of an Object
We’ve already mentioned two of the characteristics of an object
and now we mention a third … identity.
–
Behavior (methods)
–
State (data values of the instance variables)
–
Identity (the unique ID that an instance of the class has
based on its location in RAM memory - its memory
address)
If an object doesn’t have an identity, then Java couldn’t
distinguish between two different objects of the same model
class and where they are located in memory. The JVM
establishes the identity of any instance of a class when it is
constructed and RAM memory is allocated for its storage.
24
8.2 Conceptualizing Objects
Memory for data is allocated within the memory allocated for an
object. A Person object has 4 pieces of data: name, age,
address, and phone. Memory is allocated to hold the
separate values for each instance variable, depending on
their data type when the object is instantiated (constructed).
Person person1 = new Person();
name = “”
person1
age = 0
address = “”
person1 is a variable that knows
the address in RAM memory of
where the object is stored.
phone = “”
25
8.2 The JVM Keeping Track of Objects
•
The JVM knows if an object is in use by keeping track of
whether or not there are any variables referencing it. For
example, the JVM knows whether there is a variable like
person1 which references the Person object we just saw.
•
Because unreferenced objects cannot be used, Java assumes
that it is okay to delete them from memory using a process
called garbage collection. This is done automatically in Java
but not in C++ where programmers have to write the code to
return memory allocated for an object back to the system when
the instance is not needed anymore. If this isn’t done then
RAM memory can fill up when a lot of data is manipulated.
26
Section 3
The Client - Server Relationship
and
The Model - View Pattern
27
8.3 The Client - Server Relationship
•
•
When a message is sent to an object of a model class (meaning that
we use an object to call one of the methods in its model class), two
things are involved:
–
The sender (the client or view file) … usually a driver class calls
a public method of the model class using the object.
–
The receiver (the server or model file) … executes the request of
the client file by executing one of its methods and possibly
sending a value back to the client file.
Client:
–
A client’s interactions with a server are limited to sending it public
messages, because it can’t access its private instance variables.
–
A client needs to know only a servers interface, that is, the list
of methods that can be called that are supported by the
server.
28
8.3 The Client - Server Relationship
To picture this relationship, we could list the classes this way into
the categories they fit into:
Server - Model - Receiver
Client - View - Sender - Driver
Person.java
PersonDriver.java
Student.java
StudentAp.java
Auto.java
AutoDriver.java
Car.java
JavaCar.java
29
8.3 The Model-View Pattern
Many Java programs use this model-view pattern to divide up
the responsibility of different parts of a program into separate
files. We call this the server-client organization.
The responsibilities of the model class are handling “modeling an
object”, in other words the specifics of creating objects and
having them respond to messages from a client file.
The responsibilities of the view class are to decide when objects
need to be created, when messages need to be sent to them,
and “controlling the view” of the program.
The advantage is that someone can make different kinds of
driver programs, like console programs or applet programs
and change the view without changing the model class.
30
8.3 Information Hiding
Information hiding is when we don’t know what the code is in a
model class, but we know how to call methods of the model
class to manipulate an instance of the class. The class may
also be a class like the Math class that really isn’t a model
class, where we don’t know what code was written to
calculate the square root of a number, like the sqrt() method.
This means that the client programmer only knows the method
signatures of the methods in the server class, which tells
them how to call the methods to construct objects and send
messages to them.
You don’t need to know the code inside a method to call it
properly. You only need to know its method signature!
31
Section 4
More About Model Classes
32
8.4 Using A Model Class Interface
For a client programmer to use objects in a driver file, he or she
only needs to know a model class’ interface. The interface is
simply a listing of the public constructors and public methods of
the model class. Here is the Student interface:
// Constructor that initializes a Student object to default values
public Student ( )
// Constructor that initializes a Student object’s name and three test scores
public Student (String nm, int t1, int t2, int t3)
// Constructor that copies the Student object s into a new Student object.
public Student (Student s)
// Retrieves the name stored in the Student object.
public String getName ( )
// Retrieves the test score in the Student object designated by the parameter i.
public int getScore (int i)
(continued next slide)
33
8.4 The Student Class Interface Continued
(interface continued)
// Modifies the name of a Student object.
public void setName (String nm)
// Modifies a particular Student's test score.
public void setScore (int i, int score)
// returns the average of a Student object's test scores.
public double getAverage ( )
// returns the highest test score of a Student object's three test scores.
public int getHighScore ( )
// returns the STATE of a Student object.
public String toString()
The interface is all a client programmer needs to know!
34
8.4 Visibility Modifiers
private and public are visibility modifiers.
They define whether a method or instance variable can be
seen by other classes.
Instance variables should always be made private. This
promotes safety and information hiding. One way a
programmer doesn’t have access to any of the code of a
model class is when they are sometimes given to
programmers in jar files that cannot be opened but can be
added to the “build path” of a program so they can be used.
They may also be buried deep in library files.
Most methods of a model class are public, however, some
methods are private. They are called helper methods.
35
8.4 Constructors
The code for a constructor in a model class initializes all of a newly
instantiated object’s instance variables to some values.
Default constructors have empty parameter lists. If you write a
model class and don’t provide a default constructor, then Java will
provide one for you automatically behind the scenes if someone
tries to call it. In this case, Java will initialize the instance variables
to whatever values it thinks are best.
Initializing constructors have at least one parameter in their
parameter lists.
A class is easier to use when it has a variety of constructors.
36
8.4 Initializing Constructor of the Person Class
Remember the initializing constructor of the Person class.
public Person (String nm, int ag, int ad, int ph)
{
name = nm;
age = ag;
address = ad;
phone = ph;
}
Sometimes programmers don’t like to write abbreviations for the name of the
parameters that initialize the instance variables. So it is possible to use the same
names as the instance variables if you include the key word this when referring to the
instance variables.
public Person (String name, int age, int address, int phone)
{
this.name = name;
this.age = age;
Programmers are generally split on
this.address = address;
which way to do this, so there is no
this.phone = phone;
clear cut convention that is followed.
}
37
8.4 Using Chaining with Constructors
Chaining is something that programmers sometimes use to
write the code for model methods, but also classes that are
not model classes.
We will not utilize chaining in our coding exercises, however,
we do want to show you an example of what chaining is.
38
8.4 Chaining Constructors by Using this
// Default Constructor
public Student3()
{
this("", 0, 0, 0);
}
call the constructor of this class that has
4 parameters.
// Initializing Constructor
public Student3 (String name, int test1, int test2, int test3)
{
Notice that the parameter names are the same as the
this.name = name;
instance variables so this must be used to distinguish
this.test1 = test1;
between the instance variable and the parameter.
this.test2 = test2;
this.test3 = test3;
}
instance variables
parameters
// Copy Constructor
public Student3 (Student3 s)
{
this (s.name, s.test1, s.test2, s.test3);
}
(Note: This is code from the Student3 class)
call the constructor of this class that has
4 parameters.
39
8.4 Calling Model Class Methods with This
•
In a model class, this can preface the name of any instance variable
to access the data value in it or it can be used to call any method
in the class as seen here:
public double getAverage ( )
{
double average;
int sum = this.sumTests();
average = (double) sum / 3;
return average;
}
public String toString()
{
String str;
str = ”\nName: " + this.name + "\n" +
"Test 1: " + this.test1 + "\n" +
"Test 2: " + this.test2 + "\n" +
"Test 3: " + this.test3 + "\n" +
"Average: " + this.getAverage() + "\n";
return str;
}
In these two
methods, this is
used to call other
methods of the
Student class.
40
8.4 Private Helper Methods
•
Occasionally, a task performed by a method
becomes so complex that it helps to break it down
into subtasks to be solved by one or more other
methods.
•
Usually these additional methods are private
because they do not need to be called by client
programmers, but only by methods within the class
where the helper method exists.
41
8.4 Private Helper Methods
When a method is declared private, then it is meant to be called only
from other methods in the same class, not other client classes!
public double getAverage ( )
{
double average;
int sum = this.sumTests(); <-- call the private helper method
average = (double) sum / 3;
return average;
}
// PRIVATE HELPER METHOD ... CLIENT PROGRAMMERS CAN'T CALL THIS METHOD. This
method is intended to only be called by other methods of this class!!!
private int sumTests( )
{
int sum;
sum = this.test1 + this.test2 + this.test3;
return sum;
}
42
8.4 Dividing Responsibility into Classes
•
As already stated, it is a good idea to divide the code for
interactive applications into at least two sets of classes:
• view classes
• model classes
•
A view class handles the interactions with the user, such as
input and output and major algorithms that manipulate objects
of one or more model classes. An example of a view class
is PersonDriver.java or StudentApp.java or AutoDriver.java.
•
A model class represents or models the kind of objects used
or manipulated by a view class. Person.java, Student.java,
and Auto.java are all model classes.
43
8.4 The Student Class Constructors
•
The Students class has 3 constructors with these method
signatures:
•
–
public Student()
–
public Student (String nm, int t1, int t2, int t3)
–
public Student (Student s)
Note: all of these method signatures have no return types.
But what kind of value is returned by each of these
constructors???
44
8.4 The Student Class Constructors
•
The Students class has 3 constructors with these method
signatures:
•
–
public Student()
–
public Student (String nm, int t1, int t2, int t3)
–
public Student (Student s)
Note: all of these method signatures have no return types.
But what kind of value is returned by each of these
constructors???
A Student object!
45
8.4 Calling the Student Class Constructors
To declare and instantiate a Student object, we would use one
of the following lines in a driver (view) file, like
StudentAp.java:
–
Student s1 = new Student ();
–
Student s2 = new Student (“Ann”, 92, 95, 88);
–
Student s3 = new Student (s2);
The last constructor is called a copy constructor and many
programmers say you shouldn’t provide one. They say there
should be no reason to make a copy. We show you an
example of it so you know it can be done in Java.
46
8.4 Sending the getName message
Send the message to the Student object s2 that you want its
name. Since the method returns a string, store the returned
value in a string variable in case you want to do something
with it:
String nm = s2.getName();
Note: to accomplish this we use an assignment statement!!!
Note: we have to call the method with the object variable whose
name we want to get. Since we want to get the name of the s2
object, we use s2 and the “dot” (method selector) before the
name of the method.
47
8.4 Sending the setName message
Send the message to the Student object s2 that you want to
change its name. The method is a void method and doesn’t
return a value. Therefore, we will NOT use an assignment
statement. (Maybe s2 was instantiated with the wrong name
so we need to call this mutator.)
s2.setName(“Bill”);
48
8.4 Sending the toString message
Send the message to the Student object s2 that you want to
print all of its data. The method returns a String value. We
can either use an assignment statement and store the
returned value in a String variable or you can directly print the
returned value in a println statement …
String data = s2.toString();
System.out.println(data );
OR just …
System.out.println(s2.toString());
49
8.4 Implicit & Explicit toString calls
•
•
Java lets you call the toString() method explicitly or implicitly.
Explicitly call the toString method for Student object s2
System.out.println(s2.toString());
•
Implicitly call the toString method for Student object s2
System.out.println(s2);
50
8.4 Visualizing Copying Objects
Student s = new Student(“Mary”, 97, 95, 93);
Student t = new Student (s); // call the copy constructor
s
Mary
Mary
97
97
95
95
93
93
t
Here, two distinct objects exist. One referred to by s and
one referred to by t. There are no aliases. Even though we
may question why we would want a copy of the object, this
simple example shows we have two separate instances.
51
8.4 Visualizing Aliases
•
Multiple variables can point at the same object
–
Example:
Student s = new Student(“Mary”, 97, 95, 93);
Student t = s; // t is an alias for s
Mary
s
97
t
95
93
t holds a reference to the same object that s does.
To cause an object variable to no longer point at any object,
set it equal to null, as in:
s = null;
52
8.4 Setting a Variable to Null
Here is how you can visualize what happens in
memory with the following code:
Student student = new Student (“Mary”, 70, 80, 90);
student = null;
53
8.4 A simple Null-Pointer Exception
The following code produces a null-pointer exception:
Student s1;
System.out.println(“The student is ” + s1);
This is because s1 has been declared but no Student object
has been constructed for it to refer to. The program will halt
with a Null-Pointer Exception message in the console
window.
54
8.4 Avoiding Null-Pointer Exceptions
An object variable can be compared to null using the == (equal-equal)
operator. This allows a programmer to use if and while statements
to make tests before executing a segment of code:
if (s1 == null)
…. // don’t try to use s1 or a null-pointer exception will occur
else
… // process the student
while (s1 != null)
{
… process student s1 and then get another student with the
variable s1 and process it until there are no other students left.
(when no other students are left, then s1 will point at null)
}
You will learn how to work with lists of objects in the next chapter!
55
Section 5
Inheritance
Super Classes
Sub Classes
56
8.5 Class Definition Line
Here is a class definition line we have seen:
public class Student
public makes the class accessible to any file
class defines the type of Java file (there are other types)
Student is the name of class and there should not be another
class in the same package folder with that name
extends: Optional (Every class extends Object by default)
–
Java organizes classes in a hierarchy.
–
If Class B extends Class A, then Class B inherits instance variables
and methods from Class A. (see diagram next slide)
–
The Student class does not explicitly extend any other class so
there is no extends in the class definition line, but it implicitly
extends the root class of all Java classes, the Object class.
57
8.5 Superclasses & Subclasses
Here is a second example of a class definition line:
public class Square extends Rectangle
Here the Square class extends the Rectangle class so the Square
class is a subclass of the Rectangle class. We could also say that
the Rectangle class is the superclass of the Square class. These
statements should make sense, because a square is a special
case of a rectangle.
Rectangle
Parent
Square
Child
If Class B extends
Class A, then Class B
inherits instance
variables and methods
from Class A.
58
8.5 Java Classes Make Up Hierarchies
Object Class
Shape Class
Rectangle Class
Circle Class
Square Class
Wheel Class
This hierarchy diagram shows how each
class inherits characteristics from the
superclass above it in the hierarchy.
Triangle Class
Right Triangle Class
Equilateral Right
Triangle Class
59
Section 6
More About
Methods and Parameters
60
8.6 The General Form of a Method
Methods take the following form:
public or private
<visibility modifier> <return type> <method name> ( <parameter list> )
{
<implementing code>
}
Note: for any parameter in the parameter list you must include
the data type with the parameter name.
If the method returns no value, the return type should be void.
61
8.6 Public or Private ???
•
When writing a method signature, use public when the
method should be available to client programs (driver
programs or view classes), as in …
public String getName( )
•
When writing a method signature, use private when the
method is merely a “helper” method used only by other
methods within a model class, as in …
private int sumTests( )
62
8.6 When to use a return statement
When a method does NOT return a value, it is a void method
and does not need a return statement. However, sometimes
void methods use a simple return statement in the form of
return;
when we want a method to go ahead and end if some
condition becomes true.
You saw this in our a GUI program where we used the code:
if (inputStr == null)
return;
63
8.6 Void Methods - Mutator Methods
Void methods in a model class are often mutator methods,
where the parameter passed the method modifies an instance
variable of the class. Mutator methods usually use
assignment statements and don’t return a value. However,
some programmers like to have mutator methods return a
boolean value that confirms that an instance variable has truly
been modified. We’ll show you an example of that in the
Employee class later. But, remember this mutator method:
public void setName (String nm)
{
name = nm;
}
64
8.6 Accessor Methods that Return a Value
Methods that return a value in a model class are usually
accessor methods. These methods have no parameters
because nothing needs to be passed the method to be able
to return the value stored in an instance variable. Accessor
methods don’t have assignment statements, but only
have a return statement that includes an instance variable.
Remember this one:
public String getName ( )
{
return name;
}
65
8.6 Method Calls & Method Signatures
When you call a method or when you write a method signature,
parentheses are always required, even if no parameters are
needed.
When you call a method, you don’t include the data type with the
parameter! This is one of the most common mistakes of
beginning programmers.
auto1.setMake(“Ford”); <---- correct
auto1.setMake(String “Ford”); <---- incorrect
Parameters are always separated by commas if there is more
than one.
66
8.6 Mutator Stub Methods
Stub methods are used to set up skeletal, incomplete methods
that will compile and run during the early stages of program
development. Here is a stub of the mutator method setName
of the Student class that would compile and run while the
class is being developed. It is obvious that the method does
nothing at this point. (Eclipse can make stubs automatically.)
public void setName (String nm)
{
}
No return statement is needed because it is a void method
67
8.6 Accessor Stub Methods
Here is an example of an accessor stub method:
public int getScore (int i)
{
return 0;
}
For this stub we must include return 0 since the method returns
an int value or the compiler would complain and the program
wouldn’t compile. On void methods, like on the previous
slide, we don’t have to have any code in the method.
68
8.6 How many return statements?
•
If a method has a return type, the code must have at least
one return statement that returns a value of that type.
–
A return statement in a void method simply ends
the method.
–
Any type of method can have multiple return
statements. (See next slide)
69
8.6 More than One Return Statement
public static boolean isEven (int num)
{
if ( num % 2 == 0)
return true;
else
return false;
}
This code works because at least one of the branches will
be executed!
70
8.6 More than One Return Statement
public static boolean processInts (int num)
{
if ( num % 2 == 0)
return true;
if ( num % 3 == 0)
return true;
}
Eclipse would complain with this code because it knows that it
is possible that either of the if statements might not be true.
So ….
71
8.6 More than One Return Statement
So we add a return statement outside of the ifs to make sure that
at least one return statement is executed by the method.
public static boolean processInts (int i)
{
if ( i % 2 == 0)
return true;
if ( i % 3 == 0)
return true;
Any method that returns
a boolean should have
both return true and
return false statements!
return false;
}
72
8.6 The Purpose of a Parameter
The purpose of a parameter is to pass
information to a method.
The purpose of a global instance variable is
to maintain information for an object.
73
8.6 Formal and Actual Parameters
Formal parameters are listed in a method’s signature.
Actual parameters (also called arguments) are listed in the line of code
that calls the method.
Actual parameters pass their values to the formal parameters when a
method is called or invoked.
Formal params
// Client code:
Student s = new Student ( );
System.out.print(“Enter a test score: ”);
int test = reader.nextInt();
s.setScore( 1, test);
Actual params
// Server Code:
public void setScore (int i, int score)
{
if (i == 1)
test1 = test;
else if (i == 2)
test2 = test;
else
test3 = test;
}
74
8.6 The Purpose of Local Variables
Local variables provide temporary working storage for data in
a method. A good example is the getAverage( ) method. It
uses a local variable named average as temporary storage.
public double getAverage ( )
{
double average;
int sum = this.sumTests();
average = (double) sum / 3;
return average;
}
75
Section 7
Activation Records and
the Scope and Life Time
of Variables
76
8.7 Activation Records
Let’s stop and look at a diagram of a
program’s activation records while it is
running to see how memory is allocated for
actual and formal parameters when a
method is called.
77
8.7 What gets stored in an activation record?
The main things that get memory allocated in a method’s
activation record are:
•
formal parameters
•
local variables
•
memory for a return value
•
the memory address for the method to return to the previous
method
78
8.7 Activation Records
When a simple program that has a main method begins to run, an
activation record (segment of RAM memory) is allocated to hold
certain information about the main method and its variables and it is
placed on what is called the call stack. Let’s say the code is:
public void main (String [ ] args)
{
Student s1 = new Student(“Bob”, 90, 80, 70);
int highScore = s1.getHighScore();
System.out.println(“The high score is “ + highScore);
}
79
8.7 Activation Records
public void main (String [ ] args)
{
Student s1 = new Student(“Bob”, 90, 80, 70);
int high = s1.getHighScore();
System.out.println(“The high score is “ + highScore);
}
main’s
activation
record
s1 - null
high - 0
activated
When main begins to execute there are no other activation
records … just one for main. Each variable in main is allocated
memory within main’s activation record and those variables are
given default values until initialized. They aren’t initialized until
methods are called.
80
8.7 Activation Records
When the Student constructor is called, main’s activation record is
suspended and an activation record for the constructor is created
and placed on the call stack. The call stack now looks like this
with individual memory allocated for each of the parameters nm, t1,
t2, & t3 plus the memory for a new Student object that will be
returned and referenced by s1.
Student
constructor’s
activation
record
main’s
activation
record
nm, t1, t2, t3
<return value>
activated
s1 - null
high - 0
suspended
81
8.7 Activation Records
When the constructor has completed running, then its activation
record goes away by virtue of Garbage Collection and main’s
activation record is re-activated and the return value is assigned to
the variable s1. The variable high is still 0.
main’s
activation
record
s1 - Bob, 90, 80, 70
high - 0
reactivated
Then the next statement in main is executed. The method
getHighScore is called so main is suspended again while an
activation record for the method getHighScore is activated
and placed on the call stack.
82
8.7 The Code for getHighScore()
public int getHighScore()
{
int highScore;
highScore = test1;
if (test2 > highScore)
highScore = test2;
if (test3 > highScore)
highScore = test3;
return highScore;
}
(What variable in this code will get memory in getHighScore’s
activation record?)
83
8.7 Activation Records
So, when the method getHighScore is called it’s activation record
looks like this. The local variable highScore gets memory in the
activation record along with space for the value returned by the
method. The call stack now looks like this:
getHighScore’s
activation
record
main’s
activation
record
highScore
s1 - Bob, 90, 80, 70
<return value>
high - 0
activated
suspended
84
8.7 Activation Records
When the method getHighScore has completed running, then its
activation record goes away by virtue of Garbage Collection and
main’s activation record is re-activated and the return value is
assigned to the variable high.
main’s
activation
record
s1 - Bob
high - 90
reactivated
Then the next statement in main is executed and main is
suspended again while an activation record for the method
println is activated. Once println completes running, then main
is re-activated and the activation record for println goes away.
85
8.7 The Role of Objects and Classes
•
When an object is instantiated, it receives its own complete
copy of the instance variables, and when it is sent a
message, it activates the corresponding method in the class.
•
It is the role of objects to contain data and to respond to
messages.
•
It is the role of classes to provide a template for creating
objects and to store the code for the methods.
86
8.7 Instance Variables are Global
•
The instance variables in a model class are global variables.
Therefore, we say they are global in scope.
•
The instance variables in a model class don’t need to be
passed to any of its methods … they are automatically
available to all of the methods in the model class.
•
When an instance method (a method of a model class) is
executing, it does so on behalf of a particular object - an
instance of the class, and the method has complete access to
the all of an object’s instance variables because they are
global.
87
8.7 Scope and Lifetime of Variables
•
The scope of a variable is that region of the program within
which it can validly appear in lines of code.
•
The scope of all instance variables is all of the methods in the
defining class. Again, they don’t have to be passed to
methods of the defining model class.
•
The scope of a parameter or local variable is restricted to the
body of the method that declares it.
You can also have global variables in a view class that has a
main( ) method or is an applet driver file like
JavaCarRace.java. These variables don’t have to be passed
to any of the methods of the class. However, they are not
instance variables. They are just global variables.
88
8.7 Calling Model Class Methods
We have learned that:
The Server files Person.java, Student.java, Auto.java or
Car.java contain model classes and their methods are called
from some kind of driver program that is a view class.
The Client files PersonDriver.java, StudentApp.java,
AutoDriver.java and JavaCar.java are all view class files that
are drivers. These files make many calls to the constructors,
mutators, and accessors of the model class files they use.
89
8.7 Calling Model Class methods
Any model class method is called by being invoked by an instance (object
variable) of that class. Therefore, the method selector (dot) is used as in:
// Assume s1 is a Student variable. Call the void mutator method setScore without an
assignment statement.
s1.setScore(2, 95);
// Call the accessor getAverage that returns a double in an assignment statement.
double ave = s1.getAverage();
// Assume car1 is a Car variable. Call the void mutator method setSpeed without an
assignment statement.
car1.setSpeed(speed1);
// void mutator call
90
8.7 Block Scope
•
Variables declared within any compound statement that has
curly braces { }, like a method, if statement, or loop are said
to have block scope. Therefore, the variables are only
visible (valid) within the braces, not outside of them. For a
method, the block of scope for parameters and local variables
is the entire method.
•
Within the code for a method, there can also be a separate
scope inside of a loop or if statement. We call this nested
scope. If a variable is declared inside a loop or if statement
then its scope is the body of the loop or the body of the if
statement. An example follows on the next slide.
91
8.7 Block Scope Example
public void sumNumbers ( )
{
int sum = 0;
// the scope of sum is the entire method
// in the loop below the scope of i and number is the block of the for loop
for (int i = 0; i <= 10; i++)
{
System.out.print(“Enter a positive number to add to the sum: ”);
int number = reader.nextInt();
if (number < 0)
{
int negative = number; // negative has nested scope of the if
System.out.println(“Not summing” + negative + “to the sum.”);
}
sum += number;
}
System.out.println(“The sum is “ + sum);
}
92
8.7 What Variable is Out of Scope?
public void sumNumbers ( )
{
int sum = 0;
for (int i = 0; i <= 10; i++)
{
System.out.print(“Enter a positive number to add to the sum: ”);
int number = reader.nextInt();
if (number < 0)
{
int negative = number;
System.out.println(“Not summing” + negative + “to the sum.”);
}
sum += negative;
}
System.out.println(“The sum is “ + sum);
}
93
8.7 What Variable is Out of Scope?
public void sumNumbers ( )
{
int sum = 0;
for (int i = 0; i <= 10; i++)
{
System.out.print(“Enter a positive number to add to the sum: ”);
int number = reader.nextInt();
if (number < 0)
{
int negative = number;
System.out.println(“Not summing” + negative + “to the sum.”);
}
sum += negative;
// negative is out of scope!
}
System.out.println(“The sum is “ + sum);
}
94
8.7 Block Scope Example
public double calculateCircleArea (double radius )
{
double area;
area = Math.PI * Math.pow(radius, 2);
return area;
}
What is the block of scope of the formal parameter radius?
What is the block of scope of the local variable area?
95
8.7 Block Scope Example
public double calculateCircleArea (double radius )
{
double area;
area = Math.PI * Math.pow(radius, 2);
return area;
}
What is the block of scope of the formal parameter radius?
The block of the entire method.
What is the block of scope of the local variable area?
The block of the entire method.
96
8.7 The Lifetime of Variables
The Lifetime of a method variable is the period in which the
method is executing.
Method variables include:
local variables
and
formal parameters.
97
8.7 The Lifetime of Variables
•
Each time a method is called, it allocates fresh memory for
the formal parameters and local variables in that method’s
activation record.
•
When the method is over, then the memory set aside for the
parameters and local variables is freed up by garbage
collection. The activation record disappears and the memory
for the formal parameters and local variables is released back
to the system.
98
8.7 Lifetime of Instance Variables
•
The Lifetime of Instance Variables is the period during which
an object exists.
•
Every time an object is instantiated, it gets its own
complete set of memory locations to store the data values of
its instance variables.
•
When an object stops existing, the memory used to store
values for the instance variables is returned to the system
by Garbage Collection.
99
8.7 Duplicate Variable Names
•
Because the scope of a formal parameter or local variable is
restricted to a single method, the same name can be used
within several different methods without causing a conflict,
because they have different scopes. This is done because
sometimes the name of the variable is very descriptive and it
is desired to use it for clarity.
•
In the case when there is a local and a global variable with
the same name, then the local variable overrides the
global variable inside the method. To avoid this side-effect,
we can refer to the global variable using this and use the
variable name without this to refer to the local variable.
10
0
8.7 Duplicate Variable Names
public class ScopeDemo1 {
private int iAmGlobal;
public void clientMethod ( int parm1) {
int iAmLocal;
….
}
private int helperMethod (int parm1, int parm2) {
int iAmLocal;
….
}
}
Note: It is OK to use parm1 and iAmLocal in different methods. No scope conflicts.
10
1
8.7 Duplicate Variable Names
public class ScopeDemo2 {
private int iAmAVariable;
public void someMethod ( int parm)
{
int iAmAVariable;
….
iAmAVariable = 3;
this.iAmAVariable = 4;
A programmer uses the
reserved word this to refer
to the global variable
iAmAVariable.
}
public void someOtherMethod (int iAmAVariable)
{
this.iAmAVariable = iAmAVariable;
}
}
10
2
8.7 When to Use the Appropriate Variable
•
The only reason to use an instance variable is to store data
within an object.
•
The only reason to use a local variable is for temporary
working storage within a method.
•
The only reason to use parameters is to transfer information
into a method. The parameter is transferring data from a
method call into the method being executed.
•
Using global variables can sometimes cause difficult-toresolve logic errors if you are not careful. So in general, it is
better to use parameters to pass values to methods rather
than to use global variables. We use global variables many
times when all methods need the variable and then not so
10
many parameters have to be passed to a method.
3
Section 8
GUI Program Examples:
Images and Mouse Operations
10
4
8.8 Graphics and GUIs: Images
You may want to display jpeg, gif, or png graphic files in a Java
program. The following slides discuss how it can be done.
10
5
8.8 Graphics and GUIs: Images
•
To load an image into a GUI window use:
ImageIcon image = new ImageIcon (fileName);
fileName indicates the path and name of a file containing an image.
•
To paint an ImageIcon from a panel class:
image.paintIcon(this, g, x, y);
–
this refers to the panel of the program that was
constructed
–
g is the graphics context.
–
x and y are panel coordinates of where to paint the image.
10
6
8.8 GUIWindow_8_1 Demo
This first demo program will display the graphic stored in
smokey.jpeg. Make sure the following files are in your ch08
package folder:
GUIWindow_8_1.java (view class - driver)
ColorPanel_8_1.java (model class - models a ColorPanel)
smokey.jpg
Study the code in both files and then run GUIWindow_8_1.java
as your driver file then go to the next slide.
10
7
8.8 A Circle Class
•
It is useful to represent shapes as objects.
–
A shape has attributes (color, size, position). The
attributes of a shape will get stored in a shape’s
instance variables.
–
Given its graphics context, a shape can draw itself.
–
Shapes like Circle objects are then easier to manipulate.
108
8.8 The Circle Class Interface
Here is a partial listing of the methods of the Circle class.
We called a listing of the method signatures of a class - the
class’ interface.
109
8.8 The Circle Class Interface Continued
Here are other methods that can be called for the Circle class.
110
8.8 GUIWindow_8_2 Demo
Our second demo program allows us to use the Circle class to draw
or paint circles. Make sure the following files are in your ch08
package folder:
GUIWindow_8_2.java (view class - driver)
ColorPanel_8_2.java (model class - models a ColorPanel)
Circle.java
(model class - models a Circle)
Study the code in all files and then run GUIWindow_8_2.java
as your driver file. You will see the following output.
After you study
the code and run
the program go
onto the next
slide.
111
8.8 The Repaint() method
Sometimes we may need to move a shape during the run of a
program and have it redisplayed. For this to be possible Java
provides a repaint() method so that a panel or other component
can refresh itself.
repaint()forces a refresh of any GUI component (in other words it
is repainted) by invoking each object’s paintComponent method.
This is handled automatically by the JVM whenever the
component (here a ColorPanel) is moved or resized.
However, you can actually write the code to force a repaint()in
your code.
112
8.8 GUIWindow_8_3 Demo
Our third demo program, shows us how to add a mouse listener and it
is used to display the x-y coordinates of the mouse when it is
clicked in a panel. Make sure the following files are in your ch08
package folder:
GUIWindow_8_3.java (view class - driver)
ColorPanel_8_3.java (model class - models a ColorPanel)
Study the code in all files and then run GUIWindow_8_3.java
as your driver file. Particularly study the code in ColorPanel_8_3.java.
You will notice two new things: a private inner class and code that
repaints the coordinates of the mouse when the mouse is clicked
inside the output window.
After studying and running the code go onto the next slide.
113
8.8 Mouse Events
Programs can detect and respond to mouse events by attaching
listener objects to a panel. You saw this in the
ColorPanel_8_3.java code.
When a particular type of mouse event occurs in a panel, its listeners
are informed. The ColorPanel_8_3.java code used a listener class
for capturing mouse click events by having the ColorPanel_8_3
class extend MouseAdapter. This private inner class provides
code for the mousePressed() method that is automatically called
when the mouse is clicked. The method gets the coordinates in the
panel of the mouse click.
114
8.8 Mouse Events Operations
There is a listener class for capturing mouse motion and dragging
events. To use it, your class must extend MouseMotionAdapter.
This is what we will do with ColorPanel_8_4. But first let’s look at a
list of the methods that are available for processing mouse
operations.
Methods for responding to mouse events in the two classes
MouseAdapter and MouseMotionAdapter.
115
8.8 GUIWindow_8_4 Demo
This fourth demo program allows us to drag circles and reposition
them in a panel. Make sure the following files are in your ch08
package folder:
GUIWindow_8_4.java (view class - driver)
ColorPanel_8_4.java (model class - models a ColorPanel)
Circle.java
(model class - models a Circle)
Study the code in all files and then run GUIWindow_8_4.java
as your driver file. Particularly study the code in ColorPanel_8_4.java.
You will notice that there are two private inner classes, a
MouseAdapter class and a MouseMotionAdapter class. The
MouseAdapter class is needed so a circle can be selected. The
MouseMotionAdapter class is needed so that the circle can be
dragged once it is selected.
116
Chapter 8 Summary
•
Java model class definitions consist of instance variables,
constructors, and methods.
•
Constructors initialize an object’s instance variables when the
object is created.
•
A default constructor expects no parameters and sets the
variables to default values. Java provides one automatically
if you don’t.
•
Mutator methods modify the data values in an object’s
instance variables.
117
Chapter 8 Summary (cont.)
•
Accessor methods allow clients to retrieve the data values
stored in private instance variables.
•
The visibility modifier public makes methods visible to
clients.
•
The visibility modifier private makes methods invisible to
clients.
•
Helper methods are called from other methods in a model
class and are declared to be private.
118
Chapter 8 Summary (cont.)
•
Instance variables track the state of an object.
•
Local variables are used for temporary working storage
within a method.
•
Parameters transmit data to a method.
•
Actual parameters are a passed to a method when the
method is called.
•
Formal parameters appear in a method’s signature and are
referenced in the method’s code.
119
Chapter 8 Summary (cont.)
•
The scope of an instance variable is the entire class within
which it is declared.
•
The scope of a local variable or parameter is the body of
the method where it is declared.
•
The lifetime of an instance variable is the same as the
lifetime of a particular object.
•
The lifetime of a local variable or parameter of a method is
the time during which the method is active.
120