Transcript Ch4
Object State and Complexity
• Objects maintain a set of attributes.
– Position, course, speed.
– Account name, balance, transactions.
• Current set of values is the object’s state.
– Simple state: on/off.
– Complex state: chemical process controller.
• Attributes defined by fields in a class.
OOP with Java, David
J. Barnes
Defining Classes
1
State and Complexity (cont.)
• More attributes mean potentially more
complex states.
– Attribute values are often interdependent.
• Radio wave band and valid frequency range.
• Try to keep class definitions as simple as
possible.
– Break up large classes into smaller
collaborating classes.
OOP with Java, David
J. Barnes
Defining Classes
2
The Outline of a Class Definition
• Class header and class body.
• Member definitions in the body.
– Methods and fields.
// Define a class called ClassName.
class ClassName {
// Method definitions go here.
...
// Field definitions go here.
...
}
OOP with Java, David
J. Barnes
Defining Classes
3
Methods and Fields
• Methods and fields may be arranged in any
order.
– We tend to list methods before fields.
• Methods describe the behavior of instances.
• Fields are variables.
– Instance variables (most common).
– Class variables.
OOP with Java, David
J. Barnes
Defining Classes
4
Instance and Class Variables
• Each instance (object) has its own copy of
the instance variables.
– speed attribute of Ship.
– Alteration in one instance does not affect
another’s.
• All instances share a class variable.
– Altered via one instance, changed in all.
OOP with Java, David
J. Barnes
Defining Classes
5
Using the SimpleNote Class
class NoteMain1 {
public static void main(String[] args){
// Create two new SimpleNote objects
// ready for messages.
SimpleNote milk = new SimpleNote(),
swimming = new SimpleNote();
// ‘Write’ a message on one note.
milk.setMessage("We need more milk.");
// Check the message.
System.out.println(milk.getMessage());
}
}
OOP with Java, David
J. Barnes
Defining Classes
6
Defining Attributes
// A class to represent a sticky note, that
// could be stuck to a wall, door,
// refrigerator, etc. This simplified version
// just stores the message and provides access
// to it.
class SimpleNote {
// Omit the methods for simplicity.
...
// The variable used to store the text.
// The note is blank to start with.
private String message = "";
}
OOP with Java, David
J. Barnes
Defining Classes
7
Methods of the SimpleNote Class
class SimpleNote {
// Return what the message is.
public String getMessage(){
return message;
}
// Change the message.
public void setMessage(String m){
message = m;
}
// The variable used to store the text.
// The note is blank to start with.
private String message = "";
}
OOP with Java, David
J. Barnes
Defining Classes
8
Common Types of Methods
• getMessage is an accessor method.
– It returns the value of its associated attribute.
– It has a return type, matching the type of the
attribute.
• setMessage is a mutator method.
– It changes the value of its associated attribute.
– It has a formal argument, matching the type of
the attribute.
OOP with Java, David
J. Barnes
Defining Classes
9
Method Results
• Accessor methods have a return type:
– public String getMessage()
• Methods with a return type have a return
statement in their bodies:
– return message;
• The value following return is passed
back to the method caller.
OOP with Java, David
J. Barnes
Defining Classes
10
Scope
• Fields of a class have class scope (at least).
– They are freely accessible from anywhere in the
class.
• We generally choose to manipulate an
attribute only through its associated
accessor and mutator.
– This convention is not followed by all authors.
OOP with Java, David
J. Barnes
Defining Classes
11
Type Compatibility
• The expression type in a return statement
must match the return type of the method.
• The type of an actual argument must match
the type of the formal argument.
• The type of the right-hand side of an
expression must match the variable’s type
on the left-hand side.
OOP with Java, David
J. Barnes
Defining Classes
12
Primitive Types
• Major primitive types:
– boolean, char, double, int.
• Minor primitive types:
– byte, float, long, short.
• Primitive-types have no methods.
• String is not a primitive type, but occurs
frequently.
OOP with Java, David
J. Barnes
Defining Classes
13
The SimpleSwitch Class
// A class with a boolean attribute.
// A simple on/off switch.
class SimpleSwitch {
// Method definitions go here.
...
// Whether the switch is on or off.
// The switch is off by default.
private boolean on = false;
}
OOP with Java, David
J. Barnes
Defining Classes
14
The Public Interface of a Class
class SimpleSwitch {
// Turn the switch on.
public void switchOn(){
...
}
public void switchOff(){
...
}
public boolean isTheSwitchOn(){
}
...
}
OOP with Java, David
J. Barnes
Defining Classes
15
Bridging Methods
class SimpleSwitch {
// Turn the switch on.
public void switchOn(){
setOn(true);
}
...
private boolean getOn(){
return on;
}
private void setOn(boolean o){
on = o;
}
private boolean on = false;
}
OOP with Java, David
J. Barnes
Defining Classes
16
Review
• The public interface of a class should reflect
real-world usage.
– e.g., switchOn, switchOff.
• Extra methods required to bridge between
public interface and private implementation.
– Accessors and mutators may be sufficient.
• An object may invoke its own methods.
OOP with Java, David
J. Barnes
Defining Classes
17
Encapsulation
• Safe guarding the state of an object is of
primary importance.
– Access to a bibliophile’s books.
• Private attributes can be guarded by an
object.
• Access can be denied or granted to objects
of other classes, as required.
OOP with Java, David
J. Barnes
Defining Classes
18
Encapsulation (cont.)
• Java does not enforce privacy by default.
– Use private designation for all attributes.
• Control over attribute values may be
important because of knock-on effects.
– The valid range for an attribute may change as
other elements of the state are changed.
– Chemical plant process control.
– Aircraft orientation.
OOP with Java, David
J. Barnes
Defining Classes
19
Accessor Methods
• Potentially provide outside access to a
private attribute.
– public accessor available from all other classes.
– public accessor harmless for primitive type
attributes.
– private accessor limits availability to other
objects of the same class.
• Keeps implementation details hidden.
OOP with Java, David
J. Barnes
Defining Classes
20
Mutator Methods
• Necessary for external modification of a
private attribute.
• More care required with visibility.
– Public mutator potentially allows objects of all
other classes to alter the state.
– Method body could make checks to ensure
validity of mutation.
OOP with Java, David
J. Barnes
Defining Classes
21
General Form
class C {
...
public type getField(){
return field;
}
private void setField(type f){
field = f;
}
private type field;
}
OOP with Java, David
J. Barnes
Defining Classes
22
Constructors - Initializing State
• An object should start its existence in a
valid and consistent state.
• Constructors are used to achieve this aim.
• A constructor is never used to receive
messages from other objects.
– Invoked automatically as part of an object’s
creation.
OOP with Java, David
J. Barnes
Defining Classes
23
A No-Arg Constructor
class SimpleController {
public SimpleController(){
setTemperature(293.0);
}
...
public void setTemperature(double t){
temperature = t;
}
private double temperature;
}
OOP with Java, David
J. Barnes
Defining Classes
24
Constructors with Arguments
class Controller {
public Controller(){
double defaultT = 293.0;
setTemperature(defaultT);
}
public Controller(double initialT){
setTemperature(initialT);
}
...
}
OOP with Java, David
J. Barnes
Defining Classes
25
Creating Controllers
class ControllerMain3 {
public static void main(String[] args){
// Create controllers using the two
// different constructors.
Controller control1 = new Controller(),
control2 = new Controller(275.0);
...
}
}
OOP with Java, David
J. Barnes
Defining Classes
26
Overloaded Constructors - this
class Controller {
public Controller(){
// this must be the first statement.
this(293.0);
}
public Controller(double initialT){
setTemperature(initialT);
}
...
}
OOP with Java, David
J. Barnes
Defining Classes
27
Identifier Usage
• Identifiers used, so far, for:
–
–
–
–
–
–
Names of classes.
Formal argument names.
Method names.
Constructor names.
Method variable names.
Field names.
OOP with Java, David
J. Barnes
Defining Classes
28
Name Resolution
• Inside a method, look for a matching
method variable or formal argument.
• Look for a matching method or field within
the class.
• Look for another class in the current context
(current package or imported package).
• Look for a default class (e.g., String).
OOP with Java, David
J. Barnes
Defining Classes
29
Review
• Class definitions capture the behavior and
attributes of typical objects.
• Behavior modeled by method definitions.
• Attributes modeled by field definitions.
– Privacy helps to encapsulate object state.
• Accessor and mutator methods provide
access to object state.
OOP with Java, David
J. Barnes
Defining Classes
30
Review (cont.)
• Accessor and mutator methods can be
written to follow a common pattern.
• Object initialization is provided through
constructors.
– Constructors may take arguments.
• The meaning of an identifier depends upon
the context in which it is used.
OOP with Java, David
J. Barnes
Defining Classes
31