Title: ObjectOriented Design and Programming
1Objects and Classes
2Recap
- A Java application describes classes of objects
and their interactions
3Recap Objects
- Objects (instances) can be created from classes
- Objects have methods that can be invoked
- Objects have a state (they hold data)
- Objects can create other objects
4Find objects
Scrooge looked about him for the Ghost, and saw
it not. As the last stroke ceased to vibrate, he
remembered the prediction of old Jacob Marley,
and lifting up his eyes, beheld a solemn Phantom,
draped and hooded, coming, like a mist along the
ground, towards him. The Phantom slowly, gravely,
silently approached. When it came near him,
Scrooge bent down upon his knee for in the very
air through which this Spirit moved it seemed to
scatter gloom and mystery. It was shrouded in a
deep black garment, which concealed its head, its
face, its form, and left nothing of it visible
save one outstretched hand. But for this it would
have been difficult to detach its figure from the
night, and separate it from the darkness by which
it was surrounded. He felt that it was tall and
stately when it came beside him , and that its
mysterious presence filled him with a solemn
dread. He knew no more, for the Spirit neither
spoke nor moved. --Charles Dickens A Christmas
Carol
5Find objects
HARI SELDON -born in the 11,988th year of the
Galactic Era died 12,069. The dates are more
commonly given in terms of the current
Foundational Era as 79 to the year 1 F.E. Born
to middle-class parents on Helicon, Arcturus
sector (where his father, in a legend of doubtful
authenticity, was a tobacco grower in the
hydroponic plants of the planet), he early showed
amazing ability in mathematics. Anecdotes
concerning his ability are innumerable, and some
are contradictory. At the age of two, he is said
to have Undoubtedly his greatest contributions
were in the field of psychohistory. Seldon found
the field little more than a set of vague axioms
he left it a profound statistical science
--Isaac Asimov Foundation
6Find objects
Picture yourself in a boat on a river with
tangerine trees and marmalade skies. Somebody
calls you, you answer quite slowly a girl with
kaleidoscope eyes. Cellophane flowers of yellow
and green, towering over your head. Look for the
girl with the sun in her eyes and shes gone.
Lucy in the sky with diamonds. Lucy in the sky
with diamonds. Lucy in the sky with diamonds.
-- The Beatles
7Find objects
The chamber was filled with a soft light its
walls were green and silver and its roof of gold.
Many Elves were seated there. On two chairs
beneath the bole of the tree and canopied by a
living bough there sat, side by side, Celeborn
and Galadriel. They stood up to greet their
guests, after the manner of Elves, even those who
were accounted mighty kings. Very tall they were,
and the Lady no less tall than the Lord and they
were grave and beautiful. They were clad wholly
in white and the hair of the Lady was of deep
gold, and the hair of the Lord Celeborn was of
silver long and bright but no sign of age was
upon them, unless it were in the depths of their
eyes for these were keen as lances in the
starlight, and yet profound, the wells of deep
memory. --JRR Tolkien The Fellowship of the Ring
8Find objects
And on that cheek, and o'er that brow, So soft,
so calm, yet eloquent, The smiles that win, the
tints that glow, But tell of days in goodness
spent, A mind at peace with all below, A heart
whose love is innocent! --Lord Byron She Walks
in Beauty
She walks in beauty, like the night Of cloudless
climes and starry skies And all that's best of
dark and bright Meet in her aspect and her
eyes Thus mellow'd to that tender light Which
heaven to gaudy day denies. One shade the more,
one ray the less, Had half impair'd the nameless
grace Which waves in every raven tress, Or softly
lightens o'er her face Where thoughts serenely
sweet express How pure, how dear their
dwelling-place.
9Learning about objects
- Select an object, as in the lecture last week
- Describe the object in English
- Find generic names for any items on the list
- Can you categorise the items on the list?
10Objects
- Objects have properties that
- describe attributes (or states) of the object
- describe the actions the object can perform
11Classes of objects
- A class is a type or kind of object.
- All objects in the same class have the same
attributes (data and methods) - Each individual object is a member of the class.
- Each individual object is an instance of the
class.
12Recap Classes
- Classes define what objects look like they
define the methods and the data fields
(attributes) - Classes are defined by Java source code
- Programming is writing class definitions
13More classes and objects
Word Idea Space Socket Message Parameter nouns
generally?
14E.g. class of waves
/ WaveSim applet describes waves Integrating
the Schrödinger Wave Equation John L.
Richardson jlr_at_sgi.com December 1995
/ import java.awt. import java.awt.event. pu
blic class WaveSim extends java.applet.Applet
implements Runnable int wx, wy, yoff, xpts,
ypts, nx double x0, xmin, xmax, dx, ymin,
ymax, dy, xscale, yscale, tmin, t, dt double
hbar, mass, epsilon, width, vx, vwidth, energy,
energyScale complex Psi, EtoV, alpha, beta
15Software objects
A pictorial view of the class specification of
Person
Name of class
attributes
Person
name
age
gender
16Anatomy of a class
class class-name fields (instance
data) constructor(s) methods
17A class
class Timer private int hours private int
minutes private int seconds / Construct a
timer object initialised to 00000 / public
Timer() hours 0 minutes 0 seconds
0 / Return the current time of this
timer. / public String getTime() return
hours minutes seconds
18The class name
class Timer ...
convention class names start with Uppercase
Letter
The class name is an identifier.
A Java identifier must contain only letters,
digits, underscore (_) and dollar sign ()
not start with a digit
19Java Identifiers
valid number x98 howMany NUMBER_OF_POINTS yes
_S__
invalid number of points 99x birth.year ARRAY-SI
ZE
20Person.java variables, Constructors
public class Person private String firstName
/ This person's first name / private String
lastName / This person's last name
/ private int yearOfBirth / This person's
year of birth / / Constructor - create a new
(default) person / public Person() firstName
"Joe" lastName "Bloggs" yearOfBirth
0 / Constructor - create a person with the
specifed attributes / public Person(String
firstWord, String secondWord, int birthYear)
this.firstName firstWord this.lastName
secondWord this.yearOfBirth birthYear
21Person.java create objects
public static void main(String args)
/main method to test the class / String
newFirstName " ", newLastName " " int
newDOB 9 Person p1 new Person() //Joe
Bloggs System.out.println("Default person first
name " p1.getFirstName()) System.out.println(
"Default person last name " p1.getLastName())
System.out.println("Default person DOB "
p1.getYearOfBirth()) System.out.print("New
first name ") newFirstName
Keyboard.readString() System.out.print("New
last name ") newLastName Keyboard.readString(
) System.out.print("New year of birth
") newDOB Keyboard.readInt() Person p2
new Person(newFirstName, newLastName,
newDOB) System.out.println("Custom person first
name " p2.getFirstName()) System.out.println(
"Custom person last name " p2.getLastName())
System.out.println("Custom person DOB "
p2.getYearOfBirth())
22Java program that uses the Person class
- / A comment usually goes here about the program
or class/ - import java.io.
- public class CreatePersons
-
- / a comment about the method goes here/
- public static void main(String args)
-
- // instructions for the method go in here
- // for example
- // step 1 - declare two "Person" variables
- Person person1 new Person()
- Person person2 new Person(Stephanie,
Daniels, 9, female) - // the rest of the instructions go here
- // end of method main
- // end of class CreatePersons
23Fields (variables)
private int hours private int
minutes private int seconds
an identifier
field declaration access-modifier type name
private for fields
the type of value that this field can hold
convention field names start with lowercase
letter
24Field (variable) naming
fields should have meaningful names - convention
start with lower case good yearOfBirth numberOf
Seats totalTime bad yb s number
25Fields an example
object of class Timer
hours
minutes
seconds
26An instance of the Person class
The object person1
Name of (pointer to) object
person1
Values of attributes
name
attributes (instance variables)
age
gender
27Creating objects / instances
class Line private Point start private
Point end public Line(int x1, int y1, int x2,
int y2) start new Point(x1, y1)
end new Point(x2, y2) ...
28Creating objects syntax
syntax
new className(parameters)
29Another example
class Person private String fullName
private Address address ... public
Person(String name, String street,
String city) fullName name
address new Address(street, city)
30Creating objects (constructor)
- We have to create objects before we can use them.
- Look at the two statements below. What is the
difference? - Person person1
- Person person1 new Person( )
31Software engineering approach
- Classes as modules
- Encapsulation
- all data and actions are collected together into
a single module - Information hiding
- the details of the implementation (both internal
data and how the methods work) are hidden from
the user
32public versus private (English)
For a Person in English public attributes could
be those that a stranger can see - height, hair
color, eye color, sex, etc private attributes
could be those that cannot be seen by a
stranger - name, date of birth, age, religion,
politics cf also public places
33public versus private (Java)
For a Person in Java public means that a
stranger can not only see the attributes, but can
also change them. E.g. anybody can use public
places in addition to seeing them. Not a good
idea.
34Data for objects of Person class
- Each object has a number of data items (instance
variables) that hold information about attributes
of that particular object. They are usually
private to the class. - For the class Person, the instance variables are
- forename, surname, age, gender
- As code in the class they appear as
- private String forename
- private String surname
- private int age
- private int gender
35Information hiding 1
also called encapsulation
You dont know my name or age unless you ask
me! getName() getAge() but this depends on
something
Person
private attributes
name
age
gender
36Information hiding 2
methods are needed to access the hidden
attributes of Person
Person
getName()
name
setName(??)
getAge(??)
age
setAge(??)
getGender()
gender
setGender(??)
37Requesting an object to carry out an operation
- Operations are carried out by issuing a request
to an object - This is done by calling a method - tell me your
name (or age or gender) - The object uses data from
- the internal information that represents the
state of the object (the value of the objects
instance variables) - any data provided along with the request (the
arguments or parameters of the method)
38Recap Methods
- An object can call a method of another object
- Methods do something they change an attribute of
the object or return some information - Methods can have parameters
- Parameters have types
39Setting attributes 1
person1 is an object (instance) of Person class
- How do we set the name, age, gender, etc?
person1
name
Fred Smith
Fred Smith
20
age
20
male
gender
male
40Setting attributes 2
Setting the attributes of object person1 (an
instance) using the methods
person1
name
getName()
Fred Smith
Fred Smith
setName(??)
20
getAge(??)
20
age
setAge(??)
gender
getGender()
male
male
setGender(??)
41Set your age, e.g. on a form
bill
setAge(??)
25
bill
getName()
name
Joe Bloggs
setName(??)
25
getAge(??)
25
age
setAge(25)
gender
getGender()
male
setGender(??)
42Jean, what is your gender?
jean
female
getGender()
jean
name
getName()
Jean Jones
setName(??)
38
getAge(??)
age
setAge(??)
gender
female
getGender()
female
setGender(??)
43Methods
/ Return the current time of this timer.
/ public String getTime() return hours
minutes seconds
a natural language comment explaining what this
method does
/ method comment / access-modifier
return-type name (parameters) body
the type of value that this method returns
an identifier
public for most methods
convention method names start with lowercase
letter
implementation of method
44Methods an example
object of class Timer e.g. Timer myClock new
Timer()
12
hours minutes seconds
45
07
getTime()
myClock.getTime()
124507
45Methods
signature - convention start with lower case
public String getTime() return hours
minutes seconds
body
46Method categories
constructor accessor / selector (get) mutator
(set)
Each method should be in one (and only one)
category.
47Constructors
A constructor constructs and initialises a
specific object.
48Constructors
class Timer ... / Construct a
timer object initialised to 00000
/ public Timer() hours 0 minutes
0 seconds 0 ...
A constructor is a special methods that is
executed when an object is created. The name of
the constructor method is the same as the name of
the class. A constructor has no return
type. The purpose of the constructor is to
initialise the object to a valid state.
49Mutators
Also known as "set method.
A mutator changes the state (an attribute) of an
object.
50To set or calculate, you need input
Farmer standing in his field. Young hiker
approaches the fence. Hallo! How long to the
next village? Dont know. What do you mean?
How long will it take to get there? Dont
know. Hiker gives up and heads down the road.
Farmer calls out Hallo young man! Come
here! Irritated hiker returns. What do you
want? Farmer says about 3 hours Why didnt
you tell me before? .... method
estimateTimeToVillage(...)
51Setting instance (object) variables values
- public static void main(String args)
-
- // step 1 - declare two "Person"
variables - Person person1 new Person()
- Person person2 new Person()
- // step 2 - set the attributes of
"person1" - person1.setFirstName("John")
- person1.setSurname("Smith")
- person1.setAge(24)
- // step 3 - set the attributes of
"person2" - person2.setFirstName("Peter")
- person2.setSurname("Wright")
- person2.setAge(19)
52Setting an attribute of an object
- /
- set the firstName attribute of the person
- _at_param f the firstName of the person
- /
- public void setFirstName(String f)
- if (f.length()
-
- System.err.println("bad firstName
argument in 'setFirstName'") - System.exit(1)
-
- firstName f
- // end of method setFirstName
- - NOTE this could also be done in the
constructor with variables
53Accessors
Also known as "selector, get method.
An accessor provides access to some information
about the object, e.g. the value of an attribute.
It does not change the object.
54Getting instance variables values
- // step 4 - display the attributes of "person2"
- System.out.print("the second person is ")
- System.out.print(person2.getFirstName())
- System.out.print(" ")
- System.out.print(person2.getSurname())
- System.out.println(( person2.getAge() ))
//when? System.out.println() // step 5 -
leave a blank line - // step 6 - display the attributes of "person1"
- System.out.print("the first person is ")
- System.out.print(person1.getFirstName())
- System.out.print(" ")
- System.out.print(person1.getSurname())
- System.out.println(( person1.getAge()
)) //when? - // end of method main
55House example 1
house1 (Object)
House plan (Class)
house2 (Object)
house3 (Object)
56House example 2
House Class
house1.window1
house1.window2
house1.door
attributes window1 window2 door
house2.window1
house2.window2
house2.door
house3.window1
house3.window2
house3.door
57House example 3
house1.openDoor()
House plan (Class) methods openDoor()
house2.openDoor()
house3.openDoor()