USING OBJECTS What are Objects?

OBJECTS
• What are Objects?
• Properties and Capabilities (behaviours)
• Classes and Instances
• Making Instances
• A Sample Program
Objects
1
© 2006 Pearson Education
What are Software Objects?
• Building blocks of software systems
– program is a collection of interacting objects
– objects cooperate to complete a task
– to do this, they communicate by sending “messages” to each other
• Object model tangible things
– school
– car
• Objects model conceptual things
– meeting
– date
• Objects model processes
– finding path through a maze
– sorting a deck of cards
• Objects have
– capabilities (behaviours): what they can do, how they behave
– properties : features that describe the objects
Objects
2
© 2006 Pearson Education
Object Capabilities: Actions
• Objects have capabilities that allow them to perform actions
– objects are smart — they “know” how to do things
– an object gets something done only if some other object tells it to use
one of its capabilities
• Also called behaviors
Capabilities can be:
– constructors: establish initial state of object’s properties
– commands: change object’s properties
– queries: provide answers based on object’s properties
• Example: trash cans are capable of performing specific
actions
–
–
–
constructor: be created
commands: add trash, empty yourself
queries: reply whether lid is open or closed,
whether can is full or empty
Objects
3
© 2006 Pearson Education
Object Properties: State
• Properties determine how an object acts
– some properties may be constant, others variable
– properties themselves are objects — they also can receive messages
– trash can’s lid and trash are objects
Properties can be:
– attributes: things that help describe an object
– components: things that are “part of” an object
– associations: things an object knows about, but aren’t parts of the object
• State: all of object’s properties; changes if a property changes
– some don’t change, e.g., steering wheel of car
– others do, e.g., car’s color
• Example: properties of trash cans
–
–
–
attributes: color, material, smell
components: lid, container, trash bag
associations: a trash can can be associated with the room it’s in
Objects
4
© 2006 Pearson Education
Name that Object
• What are some capabilities of the objects in this room?
• What are some properties of the objects in this room?
• Which of these properties are attributes, which are
components and which are associations?
Objects
5
© 2006 Pearson Education
Classes and Instances
• Our current conception: each object corresponds directly to a
particular real-life object, e.g., a specific atom or automobile
• Disadvantage: too impractical to work with objects this way
– may be too many (i.e., modeling all atoms in the universe)
– do not want to describe each individual separately, because they may
have much in common
• Classifying objects factors out commonality
– among sets of similar objects
– lets us describe what is common once
– then “stamp out” any number of copies later
Imprints
(object instances)
Rubber stamp
(object class)
Objects
6
© 2006 Pearson Education
Object Instances
• Object instances are individual objects
– made from the class template
– one class may represent an indefinite number of object instances
– making an object instance is called instantiating that object
• Shorthand:
– class: object class
– instance: object instance (not to be confused with instance variable
(also called “data field”))
• Different instances of, say, TrashCan class may:
– have different color
– be at a different location
– have different trash inside
• So their instance variables (data fields) can have different
values
– note: object instances contain instance variables (data fields)
• two different but related uses of the word instance
Objects
7
© 2006 Pearson Education
Object Instances (continued)
• Individual instances have individual identities
– this allows other objects to send messages to a specific object
– each is unique, even though it has same capabilities
– think of classroom full of students
• Note: in Java, the value of instance variable (data field) is
always a reference to an instance, not the instance itself
– unlike in other programming languages
• A reference is just the address in memory where the
properties of the instance are stored
– also called pointer
Properties
instancea
instancei
Objects
instanceb
8
© 2006 Pearson Education
Memory Revealed
• Every instance is stored in computer’s memory
– memory is a set of consecutively numbered storage locations, each
containing a byte
– instance is stored in contiguous bytes starting at a given location
• Instance is identified and referenced by unique address of its
starting location where it was created
– address looks like 0xeff8a9f4 (hexadecimal notation, base 16)
– just like postal address represents actual home
0x00000000
0x00000001
0x00000002
0x00000080
( vertical representation )
memory address
of instance 1
memory address
of instance 2
memory address
of instance 3
( horizontal representation of memory )
Objects
9
© 2006 Pearson Education
Messages for Object Communication
• No instance is an island — it must communicate with others to
accomplish task
– properties let it know about other objects whom it can talk with
• Instances send messages to one another to invoke a
capability (i.e., to execute a task)
– method is code that implements message
– we say “call a method” instead of “invoke capability”
• Each message requires:
–
–
–
–
sender: object initiating action
receiver: instance whose method is being called
message name: name of method being called
optional parameters: more info telling method how to operate
• we’ll discuss parameters in detail in a few lectures
• Receiver can (but does not need to) send reply
– we’ll discuss return types in detail in a few lectures
Objects
10
© 2006 Pearson Education
Encapsulation
• Car encapsulates lots of information
– quite literally, under hood and behind dashboard
• So, you do not need to know how a car works just to use it
– steering wheel and gear shift are the interface
– engine, transmission, drive train, wheels, . . . , are the (hidden) implementation
• Likewise, you do not need to know how an object works to send
messages to it
• But, you do need to know what messages it understands (i.e., what
its capabilities are)
– class of instance determines what messages can be sent to it
Objects
11
© 2006 Pearson Education
Views of a Class
• Objects separate interface from implementation
– object is “black box”; hiding internal workings and parts
– interface protects implementation from misuse
Public Capability
Public Capability
Public Capability
Public Capability
Private
Properties
Public Capability
Public Capability
Note: private properties shown schematically as literally contained in an object. In reality,
they are actually stored elsewhere in memory and referenced by their addresses
• Interface: public view
– allows instances to cooperate with one another without knowing details
– is a contract: list of capabilities and documentation how to use them
• Implementation: private view
– properties that help capabilities complete their tasks
Objects
12
© 2006 Pearson Education
Notes About Java Syntax
• Reserved words
– certain words have a particular meaning in Java and cannot be used for
any other purpose
– case-sensitive (always all lower case)
class
public
new
private
extends
• Identifiers
– names used for classes, methods, and variables
– first character must be a letter or underscore
– rest may be any combination of letters, numbers, and underscores
• but no spaces
Professor
4thStreet
aPrettyLongName
a_pretty_long_name
Objects
13
© 2006 Pearson Education
Making Code More Readable
• Naming conventions
–
–
–
–
suggestions how to name things
they are intended to make code easier to read and understand
add consistency to a program
not enforced by compiler
• We use capitalization to distinguish an identifier’s purpose
– class names begin with upper case
– method and variable names begin with lower case
– in the book, instance variable (data field)s start with an underscore
• this is not common, and we discourage it because it's less readable
• different programmers have different programming style
• Use a name that represents the functionality of an object
Good Name
Poor Name
Professor
Thing (no role, purpose)
method:
teachClass
doStuff (not specific)
instance:
professor
p (too cryptic)
class:
Objects
14
© 2006 Pearson Education
A Complete Program
• Here is our first complete Java program:
/*
* Chapter 1: FirstApplication.java
*
Displays a red circle on a white background.
* The keyword extends will be explained in Chapter 3.
*/
public class FirstApplication extends wheels.users.Frame {
private wheels.users.Ellipse ellipse;
public FirstApplication () {
ellipse = new wheels.users.Ellipse();
}
//magic to let FirstApplication execute
public static void main(String[] arguments) {
FirstApplication application = new FirstApplication();
}
}
Objects
15
© 2006 Pearson Education
3 Steps to Execute Java Program
1. Editor: write program & store on disk
– Eclipse, jGRASP (also called IDE - "Integrated
Development Environment")
– Creates Program.java (text file)
2. Compiler: checks for errors & creates Java bytecode
• Eclipse does this automatically
• jGRASP has a "compile" button to push
– Creates Program.class (bytecode file)
3. Interpreter: puts (loads) Program.class in memory,
reads one bytecode at a time, translates each
bytecode to machine code, and CPU executes it
• Eclipse & jGRASP have a "run" button to push
– Program executes
Objects
16
© 2006 Pearson Education
3 Parts of a Computer
1. CPU – central processing unit
•
•
Executes each instruction
Contains IP (instruction pointer) register
• Stores address (location in memory) of next instruction
2. Memory storage unit
•
•
Stores instructions & data
Instructions & data must be piped (sent) to CPU and back
via a bus (group of wires)
• Instructions can be executed faster than they can be
moved to the CPU for execution
• Know as von Neumann bottleneck
3. I/O devices
•
Objects
Input and output
• Keyboard, monitor, mouse, etc.
17
© 2006 Pearson Education
Syntax: Declaring a Class
• Class declaration tells Java compiler that we define a
new class
– i.e., we are “declaring” our intent to “define” class that can be used as a
template to instantiate object instances
– program must include at least one class definition
public class FirstApplication extends wheels.users.Frame
• Reserved word public means that anyone can create
instance of this class
• Reserved word class tells Java that we are defining a
new class
• FirstApplication is name of the class
– named because it is our first application (program)
• extends wheels.users.Frame means:
– extends the functionality of an existing class
– in this case, we add the ability to create a red ball to the Frame class
defined in the users subpackage of package wheels (explained later)
Objects
18
© 2006 Pearson Education
Syntax: Defining a Class
• Class definition following declaration tells Java compiler how to
make instances of this class and how those instances respond
to messages
– thus, simply declaring class not enough
– we must also define what class does (i.e., how it will fulfill its purpose)
• Curly braces {} indicate beginning and end of logical block of
code; the “code body” — in this case, class definition
– represent difference between declaration and definition
– code written between curly braces is associated with class declared in front of them
public class FirstApplication extends wheels.users.Frame {
}
– this is an example of empty code block — “nothing” or “null” code is legal, i.e.,
syntactically correct, and therefore compiles, but does not do anything useful
• Java programs are composed of arbitrarily many class
definitions
– Java code is like dictionary: “declaration” of concept, followed by its definition
– no code can appear outside of a class definition
Objects
19
© 2006 Pearson Education
Constructors
• Next we need instances of our classes to do something useful
• Constructor is special kind of method that is called whenever
the class is instantiated (it creates the instance)
–
–
–
–
another object sends a message that calls constructor
constructor is the first message an object receives
this object cannot receive a constructor message again
establishes initial state of properties of the instance
• If a given class doesn't define any constructors, Java
automatically makes one for that class
– called default constructor
– initializes all instance variables (data fields) for instance to their default values
• We need to write our own constructor...
– when our application is created we want to create new object (a red circle that
appears on the screen!)
Objects
20
© 2006 Pearson Education
Syntax: Declaring Constructors
• We want to declare constructor for our class:
public class FirstApplication extends wheels.users.Frame {
public FirstApplication () {
}
}
• This is our first example of method declaration
– declares to compiler our intent to define method that implements response to
particular message
• General syntax notes:
– public means any other object can call this constructor
– FirstApplication is method’s name
– parentheses () indicate that this method doesn't need parameters (explained later)
• Constructors have special syntax:
– must always have same name as class name
• Notice: constructor is declared between curly braces that define
class
– so constructor is a special capability of the class
Objects
21
© 2006 Pearson Education
Introducing Packages
• What does class FirstApplication need in order to be
capable of fulfilling its purpose?
• A red ball on the screen!
• This has already been written for you by the textbook’s
creators
– built by someone else, but usable by anyone
– like parts in a catalog
– package is a Java catalog
• Packages are collections of related classes
– library of reusable classes (wheels)
• Packages can also contain other packages
– “nesting” provides better organization
– like sections and sub-sections in catalog
Objects
22
© 2006 Pearson Education
More on Packages
• To access classes in another package, must “qualify” class
name by package(s) it is in
– prepend each package name, separated by periods
wheels.users.Frame
package names
class name
– Frame is a class in package users, which is a subpackage of wheels
Objects
23
© 2006 Pearson Education
Object Instantiation
• Object instantiation creates an object instance from a particular class
– allows other instances to send messages to instance
– constructor is first message: makes the instance
public FirstApplication () {
ellipse = new wheels.users.Ellipse();
}
• Reserved word new tells Java to make new object instance, i.e., “call”
constructor
– fully qualified name of constructor to call is given after new; since constructors have
same name as their classes, this defines the class to instantiate
– in this case, new Ellipse is created (class in users package which is a
subpackage of wheels)
• Java calls constructor when object is made
– statements defined in constructor are executed
• Result of calling constructor is new instance of that class
Objects
24
© 2006 Pearson Education
What about the rest?
public static void main(String[] arguments) {
FirstApplication application = new FirstApplication();
}
To run the program, something must create an instance of
class FirstApplication
– the Java Virtual Machine (JavaVM) starts the program by calling the special method main
– The main method then creates an instance of class FirstApplication
• You can think of the main method as the prologue to your
application’s constructor
–
–
–
–
special method that can be called without instantiating an object
it just gets called and then constructs and sets up your application
Every program HAS to have one… it’s your starting point!
it’s a lot of magic! (for now)
• FirstApplication is the first thing created when the
program is run
– for now use wheels.users.Frame, later use something that does less work
Objects
25
© 2006 Pearson Education
More about Frames
• Frames magically do a lot of work for you
– handle input stream of events, i.e., mouse clicks and keyboard presses
– send messages to appropriate GUI component to handle event
Input
from
user
Objects
Appropriate GUI
component
(button, menu, etc.)
wheels.users.Frame
26
© 2006 Pearson Education
Syntax: Extending Frame Class
• To create your own frame, you don’t have to start from scratch
(which would be a huge amount of work) -- instead you can
extend, i.e., add on to, a default frame defined previously
– Java knows how to create a frame, but not how to create your specific
one
– also, take advantage of the work frames do for you
• Syntax for declaring extension is pretty simple, as we saw
earlier:
public class FirstApplication extends wheels.users.Frame
• Note, we give you a package to help you write your
assignments:
– wheels: graphics library used for examples in the book
• See “Textbook’s Website” link on class website
– Sun Microsystems (creators of JAVA) provides many more
• See “Java 5.0 API” (Application Programming Interface) link
Objects
27
© 2006 Pearson Education
Steps of Execution
• What’s going on inside the Java VM when we start from a
main method?
public static void main(String[] arguments)
inside main
FirstApplication application = new FirstApplication();
inside FirstApplication
ellipse = new wheels.users.Ellipse();
• What about static, void, String[] and arguments?
– we’ll talk about them in future lectures
– for now, just accept that you need them to make your program work
Objects
28
© 2006 Pearson Education
Final Code for FirstApplication
• Now that we have deconstructed it, let’s look at this code
one more time:
/*
* Chapter 1: FirstApplication.java
*
Displays a red circle on a white background.
* The keyword extends will be explained in Chapter 3.
*/
public class FirstApplication extends wheels.users.Frame {
private wheels.users.Ellipse ellipse;
public FirstApplication () {
ellipse = new wheels.users.Ellipse();
}
//magic to let FirstApplication execute
public static void main(String[] arguments) {
FirstApplication application = new FirstApplication();
}
}
Objects
29
© 2006 Pearson Education
FirstApplication (cont.)
•
Steps of execution
1. user starts program by pressing the “Run” button of the IDE (Integrated
Development Environment)
2. method main(…) is called by JavaVM
3. FirstApplication is instantiated by the new command
4. constructor FirstApplication() is activated upon instantiation of class
FirstApplication
5. instance of Ellipse is created by activating its constructor
6. FirstApplication’s constructor is now finished, FirstApplication
(and anything constructed in it) runs until program quits (by pressing the
“quit” button located at the bottom of the frame)
Objects
30
© 2006 Pearson Education
Class Exercise
• Modify class FirstApplication so it displays a rounded
red rectangle on a white background.
– Check out the wheels package (see “Textbook’s Website” link from
class web page) for details on classes & methods
Objects
31
© 2006 Pearson Education
OBJECTS (continued)
• Views of a Class
• Defining Your Own Class
• Declaring Instance Variables (Data Fields)
• Declaring Methods
• Sending Messages
Objects
32
© 2006 Pearson Education
Example: The ICSMobile
• How can we best design and build the ICSMobile?
• Think object-oriented: the ICSMobile is an object
with properties and capabilities
• Create a class to model the ICSMobile and then
make instances of that class
Objects
33
© 2006 Pearson Education
Specifications of the ICSMobile
• A basic specification of the ICSMobile:
The ICSMobile should have an engine and wheels so that it can move
around. It also should have doors so that people can get in and out. The
ICSMobile should have the ability to move forward and backward. It
should also be able to turn left and right.
• What are the ICSMobile’s properties?
– engine, wheels, doors
• What are the ICSMobile’s capabilities?
– move forward, move backward, turn left, turn right
– don’t forget the constructor — all objects have the ability to be
constructed (when sent a message to do so by another object)
• What does this look like in Java?
– remember, properties are represented by instance variables
– capabilities are represented by methods
– Let’s see...
Objects
34
© 2006 Pearson Education
Simple Syntax for ICSMobile
Note: The point of this to show an outline of what a generic class looks like.
package machinePackage.carPackage;
/** Models a vehicle that can move and turn. */
public class ICSMobile {
// instance variables (data fields)
private Engine engine;
private Door driverDoor;
private Door passengerDoor;
private Wheel frontDriverWheel;
private Wheel rearDriverWheel;
private Wheel frontPassengerWheel;
private Wheel rearPassengerWheel;
public ICSMobile() { // constructor
// construct the component objects
engine = new Engine();
driverDoor = new Door();
passengerDoor = new Door();
frontDriverWheel = new Wheel();
rearDriverWheel = new Wheel();
frontPassengerWheel = new Wheel();
rearPassengerWheel = new Wheel();
}
Objects
35
© 2006 Pearson Education
Simple Syntax for ICSMobile (cont.)
// declare and define methods
public void moveForward() {
// code to move ICSMobile forward
}
public void moveBackward() {
// code to move ICSMobile backward
}
public void turnLeft() {
// code to turn ICSMobile left
}
public void turnRight() {
// code to turn ICSMobile right
}
}
Objects
36
© 2006 Pearson Education
ICSMobile Syntax Explained (1 of 5)
package machinePackage.carPackage;
– package keyword tells Java that this class should be part of a package
– in this case, the package (folder) is machinePackage and the
subpackage (subfolder) is carPackage
– so the code would be stored in the subfolder called carPackage
/** ... */
– everything between /* and */ is a block comment
• useful for explaining specifics of classes
• compiler ignores comments
• but we comment for people who want to read our code
– class ICSMobile has a kind of block comment called a documentation
comment
• appears at top of class
• explains purpose of class
public class ICSMobile {
– declares that we are about to create a class named ICSMobile
– public indicates that any other object can create instance of this class
Objects
37
© 2006 Pearson Education
ICSMobile Syntax Explained (2 of 5)
• Everything associated with class must appear within
the curly braces, the body
{ all instance variables (data fields) and methods;
} // no code may appear outside braces
//
...
– everything on the same line after // is a comment
– known as inline comment
– describes important features in code
private Engine engine;
– declares an instance variable named engine of type Engine
– reserved word private
• indicates that instance variable (data field) will be available only to
methods within this class
• other objects do not have access to engine
• ICSMobile “encapsulates” its engine
– remember, properties are objects themselves
• every object must be an instance of some class
• class of instance variable (data field) is called its type
– type determines what messages this property understands
Objects
38
© 2006 Pearson Education
ICSMobile Syntax Explained (3 of 5)
– name of instance variable is engine
• Note: We don’t follow the book’s coding convention to prefix all instance
variables (data fields) with an underscore, “_”
private Door driverDoor,
private Door passengerDoor;
– Java allows to declare multiple instance variables of the same type and
just separate them with a comma, but we recommend to declare each
variable separately
– driverDoor and passengerDoor are instance variables of type Door
public ICSMobile() {…}
–
–
–
–
constructor for class ICSMobile
remember: constructor is first message sent to instance
must have the same identifier as its class
() makes it a method
• Standard convention: variable names start with lowercase
letter and all new words in the name are capitalized
Objects
39
© 2006 Pearson Education
ICSMobile Syntax Explained (4 of 5)
engine = new Engine();
– reserved word new tells Java that you want to make a new
instance
– equals sign, =, means variable on left side “gets” value of right
side
– so value of instance variable engine will be new instance of
class Engine
• i.e., engine “gets” a new Engine
– constructors initialize the new instance
• i.e., construct initial state
– note: Constructor ICSMobile() refers directly to engine
• all methods, including constructor, have direct access to all of their
class’ instance variables (data fields)
– all other instance variables are initialized in the same way
Objects
40
© 2006 Pearson Education
Another way to initialize ICSMobile
•
Variables can be initialized where they are declared
•
Consider our ICSMobile:
package machinePackage.carPackage;
/** Models a vehicle that can move and turn. */
public class ICSMobile {
// instance variables
private Engine engine = new Engine();
private Door driverDoor = new Door();
private Door passengerDoor = new Door();
private Wheel frontDriverWheel = new Wheel();
private Wheel rearDriverWheel = new Wheel();
private Wheel frontPassengerWheel = new Wheel();
private Wheel rearPassengerWheel = new Wheel();
public ICSMobile() {}
•
Advantages of the latter form:
–
uninitialized variables are often cause of errors,
•
–
–
giving them a value right away is a good practice (see later)!
the code is shorter, more readable
empty constructor can be omitted (Java inserts one)
Objects
41
© 2006 Pearson Education
ICSMobile Syntax Explained (5 of 5)
public void moveForward() {…}
– declares a method named moveForward
– reserved word public indicates this method is visible to anyone
• any other object that knows an instance of this class can send it
moveForward message
– reserved word void means that this method does not return any result
• some methods return values to calling method
• later we will learn more about return types
• constructor declaration does not need to state return value, it returns the
new object instance
– moveForward is name of the method
– anything inside curly braces is part of method definition’s body
• Standard convention: method names start with lowercase
letter and all new words in the name are capitalized
Objects
42
© 2006 Pearson Education
ICSMobile
• That’s it for the basic skeleton of class ICSMobile!
• Now you know how to write a class with properties and
capabilities
– can declare variables (data fields) and methods
• By the end of the course, you will be able to write the full
ICSMobile class!
– will be able to fully define methods
– will add a few more instance variables and change methods a little
– but... basic structure will be the same!
• Next we look at representation of our three types of properties
– components
– associations with other objects
– attributes
Objects
43
© 2006 Pearson Education
Object Relationships and Diagrams
• Our specification says that ICSMobile has an engine, doors,
and wheels; these are components
• We can say that the ICSMobile is composed of its engine,
doors, and wheels
• Containment is a way to associate objects with one another
• How do you determine containment?
– class ICSMobile has an instance variable of type Engine
– class ICSMobile creates an instance of type Engine
– therefore, ICSMobile is composed of an Engine
• How do we diagram containment?
– UML (Unified Modelling Language)
ICSMobile
Objects
engine
44
Engine
© 2006 Pearson Education
In the City…
• Suppose we have a City object.
• City contains and therefore constructs
–
–
–
–
parks
schools
streets
cars, e.g., ICSMobiles
• Therefore, City can call methods on
–
–
–
–
parks
schools
streets
ICSMobiles
• But, relationship is not symmetric!
• Park, School, Street and ICSMobile classes don’t
automatically have access to City -- i.e., they can’t call methods
on City
• How can we provide ICSMobile with access to City?
Objects
45
© 2006 Pearson Education
The Association Relationship
• Answer: We associate the ICSMobile with its City
• How do you determine the association relationship?
– we’ll add to class ICSMobile an instance variable of type City
– class ICSMobile doesn’t create its instance of type City; therefore,
City won’t be a component of ICSMobile
– we say: class ICSMobile “knows about” City
– tune in next lecture to see how to set up an association (“knows about”)
relationship in Java
• How do we diagram association?
– UML (Unified Modelling Language)
ICSMobile
Objects
City
city
46
© 2006 Pearson Education
Attributes
• The ICSMobile has certain attributes
– color, size, position, etc.
• Attributes are properties that describe the
ICSMobile
we’ll add to class ICSMobile an instance variable of type Color
ICSMobile is described by its Color
different than “is composed of” relationship
class ICSMobile doesn’t contain its Color, nor is it associated with it
we say: Color is an attribute of class ICSMobile
class ICSMobile may set its own Color or another class may call a method on
it to set its Color
– actual color of ICSMobile is an attribute, and it is also instance of Color class
–
–
–
–
–
–
• all instance variables are instances!
• How do we diagram an attribute?
ICSMobile
Color color
– because attributes don’t have the full weight of other object relationships, we just
put their type and name in line, without an arrow for the reference
Objects
47
© 2006 Pearson Education
Class Box
• Used to depict schematically a class
– rectangle for a class (like index card) with name of class at the top
– properties of class in next section (types, names of instance variables)
– capabilities (methods) of class in bottom section
• note: constructor can be assumed
• Example of class ICSMobile with the properties discussed:
ICSMobile
Engine engine
Door driverDoor
Door passengerDoor
Wheel frontDriverWheel
Wheel rearDriverWheel
Wheel frontPassengerWheel
Wheel rearPassengerWheel
City city
Color color
moveForward()
moveBackward()
turnLeft()
turnRight()
Objects
48
© 2006 Pearson Education
Class Diagrams
• A class diagram shows how classes relate to other classes
–
–
–
–
–
rectangle represents class as class box
important relationships are connected by lines with arrows
important properties have name on top of the lines
attributes have type and identifier (but don’t show references)
UML (Unified Modelling Language)
ICSMobile
Color color
moveForward()
moveBackward()
turnLeft()
turnRight()
city
<<knows about>>
City
engine
<<contains an>>
Engine
Note: Properties and capabilities
of City and Engine have been
omitted for clarity
Objects
49
© 2006 Pearson Education
Packages and Accessing Classes
• Qualified name of ICSMobile
– its qualified name is: machinePackage.carPackage.ICSMobile
– the qualified name of a class includes the names of all the packages it
belongs to (e.g., machinePackage and its sub-package carPackage)
• To access a class, you can refer to it by its qualified name
• You don’t need to qualify class in same package as current
class, or a class that is imported
– Engine is in package machinePackage.carPackage
– declaration package machinePackage.carPackage; at the top of
ICSMobile class definition makes ICSMobile part of
machinePackage.carPackage package
– ICSMobile can refer to machinePackage.carPackage.Engine as,
simply, Engine
• Similarly, you don’t need to qualify an imported class
– import wheels.users.Frame; can occur after package declaration
– then ICSMobile can use simply Frame
Objects
50
© 2006 Pearson Education
Working With Variables
• Variables in Java are like variables in math
– hold single (reference to a) value that can vary over time
– but need to have previously defined value to be used
• Remember ICSMobile? Creating an instance variable was
done in two parts
1. declaration: private Engine engine;
2. initialization: engine = new Engine();
• What is value of engine before step 2? What would happen
if step 2 were omitted?
• Java gives all variables a default value of null
– i.e., it has no useful value
– null is another reserved word in Java
– it means a non-existent memory address
Objects
51
© 2006 Pearson Education
Uninitialized Variables and null
• If you forget to give your variables initial values, Java VM
will reward you with a runtime error in the form of a
NullPointerException
– runtime errors are problems that occur while your program is running
– i.e., your program compiled successfully, but it does not execute
successfully
– for now, when runtime errors occur, your program is usually stopped by
Java VM
• NullPointerException
– if you get such an error, make sure you have initialized all of your
object’s instance variables!
– most common occurrence of a NullPointerException is trying to
send a message to an uninitialized variable
WATCH OUT!
Objects
52
© 2006 Pearson Education
Assigning Values to Variables
• Assignment provides a way to change the value of variables
– replaces current value of variable with new value
– example: engine = new Engine();
– we say: engine “gets” a new instance of class Engine
• As we’ve seen, equals sign, =, is Java’s syntax for
assignment
– variable on left side of equals “gets” value of right side
– not like equals in Math! (which denotes equality of left- and right-hand
sides)
• Using = with new
– calls the constructor of the class
– constructor results in new instance of class
– new instance is value assigned to variable
• Using = without new
– assigns from one value to another
– example: exteriorColor = interiorColor;
– makes the exterior color have the same value as the interior color
Objects
53
© 2006 Pearson Education
Working With Methods
• We know how to declare methods, but how do we call them?
How can we send messages between objects?
• Syntax is variableIdentifier.methodIdentifier();
public class City {
private ICSMobile mobile111;
public City() {
mobile111 = new ICSMobile();
mobile111.moveForward();
}
}
• Sending a message (“calling moveForward on mobile111”)
causes code associated with method to be executed
mobile111.moveForward() is a method call
•
•
•
•
•
mobile111 is message’s receiver (one being told to move)
dot (“.”) separates receiver from message name
moveForward is name of message to be sent
() denotes parameters to the message
more on parameters next lecture! woo hoo!
Objects
54
© 2006 Pearson Education
this keyword (1 of 2)
• What if we want one method in a class to call another method
in the same class?
– let’s say we want the ICSMobile to have a turnAround() method
– will want the turnAround() method to call the ICSMobile’s own
turnLeft() or turnRight() method twice
• In order for current instance to be receiver of message, we
need a way to refer to it
• Reserved word this is shorthand for “this instance”
– current instance, this, is receiver of message
– so what we’re really doing with this is having an instance send a
message to itself
Objects
55
© 2006 Pearson Education
this keyword (2 of 2)
• Example of using this to call a method on the current
instance of the class
public void turnAround() {
this.turnLeft();
this.turnLeft();
}
this.turnLeft();
– tells the current class to execute the code in its turnLeft() method
– since calling your own methods is common, using this is optional
– this.turnLeft() and turnLeft() do the same thing
– using this makes it more clear
public void turnAround() {
turnLeft();
turnLeft();
}
may be shorter, but not as clear
• Now that we’ve seen how to call methods, let’s do something
with the ICSMobile...
Objects
56
© 2006 Pearson Education
Example: Driving Around Kaimuki
• Given a “world” where the ICSMobile moves only along the
roads defined by a regular grid:
– think of it as a simplified city map: Assume the streets of Kaimuki are all
the same length and go only horizontally and vertically
– ICSMobile can move forward in direction it is facing and can turn 90
degrees left or right
– can move only one block at a time
• Get ICSMobile to Coffee Talk (corner of 12th and Waialae)
and back, given…
• these initial conditions:
– ICSMobile starts at corner of Koko Head and Pahoa facing north
Objects
Koko
Head
12th
Waialae
Harding
Pahoa
57
© 2006 Pearson Education
Example: Analyzing the Problem
• Most important first step is to analyze and understand the
problem
– ask questions about specifications of problem
– restate nature of problem in your own words
• Understanding the specifications
– only horizontal and vertical movement is allowed
– ICSMobile can only turn in right angles
– moves from intersection to intersection
• Understanding the problem
– must move two blocks North and one block West to get to 12th and
Waialae
– must move two blocks South and one block East to get back to Koko
Head and Pahoa
• Solution:
Objects
58
© 2006 Pearson Education
Example: Pseudocode
• You can describe how to complete this task at some level of
detail in English; this is called “pseudocode”
tell ICSMobile to move forward one block
tell ICSMobile to move forward one block
tell ICSMobile to turn left
tell ICSMobile to move forward one block
tell ICSMobile to turn left
tell ICSMobile to move forward one block
tell ICSMobile to move forward one block
tell ICSMobile to turn left
tell ICSMobile to move forward one block
• Pseudocode is more detailed than the initial problem
specification, but not as detailed as the code itself
– multiple levels of pseudocode may be used
– decomposition process is called stepwise refinement because each
successive level is more detailed or refined
– good programming flows from specification to pseudocode to actual
code
• Now that we’ve pseudocoded, let’s see the actual code...
Objects
59
© 2006 Pearson Education
Code Reusability
• Is our pseudocode reusable? What happens if we want to go
back?
• The ICSMobile is not pointing in the same direction after the
trip as it was in the beginning!
– We have changed the state of the ICSMobile
– We should add a left turn at the end so that the ICSMobile is pointing in
the same direction as in the beginning:
Objects
60
© 2006 Pearson Education
Reusable Pseudocode
• Here’s our new pseudocode:
tell ICSMobile to move forward one block
tell ICSMobile to move forward one block
tell ICSMobile to turn left
tell ICSMobile to move forward one block
tell ICSMobile to turn left
tell ICSMobile to move forward one block
tell ICSMobile to move forward one block
tell ICSMobile to turn left
tell ICSMobile to move forward one block
tell ICSMobile to turn left
• The final left turn leaves the ICSMobile facing in the original
direction
• Always think about what effects a method has on the state of
an object
– Other parts of the code depend on correct execution
– Simulate on paper to be sure
Objects
61
© 2006 Pearson Education
Syntax for Trip to Coffee Talk
/**
* This class models the process of a ICSMobile
* driving from the corner of Koko Head and Pahoa
* to Coffee Talk (at 12th and Waialae) and back.
*/
public class TripToCoffeeTalk {
private machinePackage.carPackage.ICSMobile mobile111;
public TripToCoffeeTalk() {
mobile111 = new machinePackage.carPackage.ICSMobile();
}
public void takeTrip() {
mobile111.moveForward();
mobile111.moveForward();
mobile111.turnLeft();
mobile111.moveForward();
mobile111.turnLeft();
mobile111.moveForward();
mobile111.moveForward();
mobile111.turnLeft();
mobile111.moveForward();
mobile111.turnLeft();
}
}
© 2006 Pearson Education
Objects
62
Syntax for Application
/**
* This class exists to start everything up.
*/
public class TripApplication extends wheels.users.Frame {
private TripToCoffeeTalk trip;
public TripApplication() {
trip = new TripToCoffeeTalk();
trip.takeTrip();
}
public static void main ( String[] arguments ) {
TripApplication tripApplication = new TripApplication();
}
} // end of class TripApplication
Objects
63
© 2006 Pearson Education
TripToCoffeeTalk Syntax Explained
• Note name of class:
– describes process that object models
– a TripToCoffeeTalk
– usually, you would have ability to drive to Coffee Talk be a capability of
ICSMobile, but we haven’t yet learned how to extend functionality of
existing class
• Basic rundown:
– declares instance variable of type ICSMobile
– initializes ICSMobile instance in constructor
– calls methods on ICSMobile instance in takeTrip method
mobile111.moveForward();
– message sent by instance of TripToCoffeeTalk
– message sent to instance of ICSMobile
– TripToCoffeeTalk tells its contained ICSMobile instance to move
forward
– all other method calls are similar!
Objects
64
© 2006 Pearson Education
TripApplication Syntax Explained
• Only purpose of the application is to start everything up:
// create the instance
trip = new TripToCoffeeTalk();
// call method on the instance
trip.takeTrip();
• This instance, in turn, calls methods (moveForward,
turnLeft, etc.) on its contained mobile111 instance
Objects
65
© 2006 Pearson Education
Steps of Execution
• What’s going on inside the JavaVM?
Main method instantiates TripApplication
mobile111 is
created and told to
take a trip
TripApplication
trip = new TripToCoffeeTalk();
trip.takeTrip();
inside
takeTrip()
mobile111.moveForward();
mobile111.moveForward();
. . .
• takeTrip method ends, so control returns to TripToCoffeeTalk
constructor
• TripToCoffeeTalk constructor ends, so control returns to
TripApplication constructor
• TripApplication constructor ends, so main method ends and so does
the program
Objects
66
© 2006 Pearson Education