DEPARTMENT OF COMPUTER SCIENCE
DEPARTMENT OF COMPUTER SCIENCE
Agenda
Defining simple classes Instance variables and methods Objects Basic UML notation for classes and objects Object references
COMP1008 Classes and References
2006, Graham Roberts
2006, Graham Roberts
DEPARTMENT OF COMPUTER SCIENCE
DEPARTMENT OF COMPUTER SCIENCE
Reading
You should be reading:
Part I chapters 6,9,10
Classes & Objects
We want to design programs in terms of classes and objects. Write the classes using the programming language.
Define structure and behaviour.
And browsing:
Part IV chapter 30
Use the objects when the program runs.
2006, Graham Roberts
2006, Graham Roberts
DEPARTMENT OF COMPUTER SCIENCE
DEPARTMENT OF COMPUTER SCIENCE
Class
Defines the structure and behaviour of an instance object.
A collection of instance variables to represent the state of the object. A collection of instance methods, which can be called on the object.
Abstraction
A representation or model that includes the important, essential or distinguishing aspects of something while suppressing or ignoring less important, immaterial or diversionary details. Removing distinctions to emphasise commonality. Leaving out of consideration one or more properties of a complex object so as to attend to others. The process of formulating general concepts by abstracting common properties of instances.
Acts as a template or blueprint. An object is an instance of one (and only one) class. A class may have many instance objects.
2006, Graham Roberts
2006, Graham Roberts
DEPARTMENT OF COMPUTER SCIENCE
DEPARTMENT OF COMPUTER SCIENCE
Abstraction and Classes
Classes represent abstractions. Abstraction is used to separate the essential from the full detail. They provide a selective and simplified view of the concepts being represented as objects. Good OO programming is all about identifying and using the right abstractions.
Class Role
To Represent
Entities and things (Person, Account, Date, String, etc.) Strategies and behaviours Data structures Relationships
To Structure
Divide code into manageable chunks Enforce encapsulation and information hiding
2006, Graham Roberts
2006, Graham Roberts
DEPARTMENT OF COMPUTER SCIENCE
DEPARTMENT OF COMPUTER SCIENCE
Notations
Classes can be represented by:
Binary code
produced by the compiler (.class files) not human readable
UML - The Unified Modeling Language
De-facto standard notation
A small subset introduced in COMP1008, much more in COMP2010 next year. Maintained by the OMG (Object Management Group), see www.uml.org
Source code
the programming language
Modelling language
formal: UML informal: notes, diagrams, doodles
Different levels of abstraction
Source code embodies all the details Modelling language gives a more abstract view
Allows design to be represented without having all the detail of code
2006, Graham Roberts
UML provides a complete language for describing object-oriented models (like a programming language). Also provides a visual notation for displaying models.
This is what we are interested in here.
9
2006, Graham Roberts
10
DEPARTMENT OF COMPUTER SCIENCE
DEPARTMENT OF COMPUTER SCIENCE
UML Class Icons
UML Class Diagrams
Show classes and their relationships.
inheritance relationship
association relationship minimal icon Instance variables are often referred to as attributes. Amount of detail in icon can be selected depending on context.
2006, Graham Roberts
11
2006, Graham Roberts
12
DEPARTMENT OF COMPUTER SCIENCE
DEPARTMENT OF COMPUTER SCIENCE
Example Java Class
import java.util.ArrayList; class Person { private String firstName; private String familyName; private ArrayList<String> emailAddresses; public Person(String firstName, String familyName) { this.firstName = firstName; this.familyName = familyName; this.emailAddresses = new ArrayList<String>(); } public String getFullName() { return firstName + " " + familyName; } public void addEmailAddress(String address) { emailAddresses.add(address); } public ArrayList<String> getEmailAddresses() { return new ArrayList<String>(emailAddresses); } }
2006, Graham Roberts
Class Person
Instance Variables
By convention a class name always starts with a capital letter. Instance objects can be created using:
Person person = new Person(Arthur,Dent) ;
Create new Person object initialised to given name.
Constructor (to initialise a new instance object)
As many objects as you need can be created.
Instance Methods
Each object represents a distinct person.
13
2006, Graham Roberts
14
DEPARTMENT OF COMPUTER SCIENCE
DEPARTMENT OF COMPUTER SCIENCE
A Person Object
Has three private instance variables. And three public instance methods that can be called. And a constructor used to initialise the object.
UML Object Icon
arthur : Person
rstName = "Arthur" familyName = "Dent" emailAddresses = empty list
Objects
Each object has its own separate set of variables. Each object has its own identity. Each object is independent.
arthur : Person
rstName = "Arthur" familyName = "Dent" emailAddresses = empty list
id : Class used to label icon. id can be omitted.
zaphod : Person
rstName = "Zaphod" familyName = "Beeblebrox" emailAddresses = list size innite
Class name underlined. Can show instance variable values.
ford : Person
rstName = "Ford" familyName = "Prefect" emailAddresses = list size 42
2006, Graham Roberts
15
2006, Graham Roberts
16
DEPARTMENT OF COMPUTER SCIENCE
DEPARTMENT OF COMPUTER SCIENCE
UML Object Diagram
Shows a snapshot of objects and links during execution of program
: AddressBook
entries = list size 3
Private
A class defines a scope. Declaring a method or variable private means that it can be accessed only within the scope of the class.
This means within a method body or an instance variable initialisation expression.
zaphod : Person
rstName = "Zaphod" familyName = "Beeblebrox" emailAddresses = list size innite
arthur : Person
rstName = "Arthur" familyName = "Dent" emailAddresses = empty list
At runtime objects implement the scope rules.
Class + compiler + type checking ensures behaviour must conform.
ford : Person
rstName = "Ford" familyName = "Prefect" emailAddresses = list size 42
The internal state of an object should be private and changed only by the objects methods.
The state is represented by the values of the instance variables.
17
2006, Graham Roberts
2006, Graham Roberts
18
DEPARTMENT OF COMPUTER SCIENCE
DEPARTMENT OF COMPUTER SCIENCE
Public
Methods and variables declared public can be accessed by anything that has a reference to an object of the class.
Variables belong to an object. Methods are called on an object.
Encapsulation
Public and private are how encapsulation is enforced. Good practice states:
Instance variables should always be private. Only a minimal number of methods should be made public. Limit a name to the minimum scope.
They form the public interface of objects of the class.
The services the object can perform.
Why?
19
To enforce design decisions. To protect against mistakes. Information hiding. To avoid misuse of classes and objects. Experience demonstrates encapsulation is a very important design strategy.
20
2006, Graham Roberts
2006, Graham Roberts
DEPARTMENT OF COMPUTER SCIENCE
DEPARTMENT OF COMPUTER SCIENCE
Questions?
Encapsulation is a technique for minimising interdependencies among separately written modules by defining strict external interfaces. The external interface acts as a contract between a module and its clients. If clients only depend on the interface, modules can be re-implemented without affecting the client. Thus the effects of changes can be confined. Synder 1986
2006, Graham Roberts
21
2006, Graham Roberts
22
DEPARTMENT OF COMPUTER SCIENCE
DEPARTMENT OF COMPUTER SCIENCE
Type Person
Person is a actually a new type. This allows Person to be used for declarations such as: Person person = new Person(Ford, Prefect); In fact, Person is a User Defined Type.
Object References
Person person = new Person(Ford, Prefect) ;
person:
ford : Person
rstName = "Ford" familyName = "Prefect" emailAddresses = empty list
Object Reference
2006, Graham Roberts
23
2006, Graham Roberts
24
DEPARTMENT OF COMPUTER SCIENCE
DEPARTMENT OF COMPUTER SCIENCE
References
A variable of a class type holds a reference to an object.
A reference is a pointer (form of memory address).
Class Type Assignment
Assignment means storing a reference to a different object:
ford : Person
person1:
rstName = "Ford" familyName = "Prefect" emailAddresses = list size 42
Variable doesnt hold the object itself. The variable can go out of scope but the object can still exist (providing it is referenced by some other variable). One object can be referenced by several references and, hence, variables.
person2:
arthur : Person
rstName = "Arthur" familyName = "Dent" emailAddresses = empty list
person1 = person2
2006, Graham Roberts
25
2006, Graham Roberts
26
DEPARTMENT OF COMPUTER SCIENCE
DEPARTMENT OF COMPUTER SCIENCE
So,
When you declare a variable of class type, you get a container that holds an object reference. Assigning an object to a variable means storing a reference to the object in the container.
Null Reference
null keyword. No object is referenced, so no methods can be called. Person person = null; Default value if variable not initialised.
person:
2006, Graham Roberts
27
2006, Graham Roberts
28
DEPARTMENT OF COMPUTER SCIENCE
DEPARTMENT OF COMPUTER SCIENCE
NullPointerException
Caused by calling method on a null reference. No object, so no method can be called. If the error occurs find out why the variable is not referencing an object.
Questions?
2006, Graham Roberts
29
2006, Graham Roberts
30
DEPARTMENT OF COMPUTER SCIENCE
DEPARTMENT OF COMPUTER SCIENCE
Calling methods
Given an object reference, a method can be called:
Person person = new Person(Arthur, Dent); String name = person.getName();
Object Reference Parameters
You can pass an object reference as a parameter to a method:
void someMethod(Person aPerson) { // Use aPerson in method body }
Only methods provided by class Person can be called.
Those methods declared by Person, and inherited methods (as we will see later).
A parameter variable is declared as normal.
2006, Graham Roberts
31
2006, Graham Roberts
32
DEPARTMENT OF COMPUTER SCIENCE
DEPARTMENT OF COMPUTER SCIENCE
Parameters & References
Method call: someMethod(person); person:
Object Parameters
The parameter value is an object reference, not an object. The parameter variable is initialised to hold a copy of the reference. The object is not copied.
The reference is copied not the object.
ford : Person
rstName = "Ford" familyName = "Prefect" emailAddresses = list size 42
void someMethod(Person aPerson) { ... }
Two references to same object.
aPerson:
2006, Graham Roberts
33
2006, Graham Roberts
34
DEPARTMENT OF COMPUTER SCIENCE
DEPARTMENT OF COMPUTER SCIENCE
Consequences
If an object reference is passed as a parameter then:
Changing the object inside the method changes the object outside the method. They are the same object!
Remember Primitive Types?
Values of primitive types (int, char, long, boolean, etc.) are stored directly in variables using a binary representation. They are not objects. You cant have references to values of primitive types.
But there are classes to represent values of primitive types. Class Integer, Double, Character, etc.
Dont forget that arrays are objects.
Changing elements in an array parameter changes the array outside the method.
2006, Graham Roberts
35
2006, Graham Roberts
36
DEPARTMENT OF COMPUTER SCIENCE
DEPARTMENT OF COMPUTER SCIENCE
Primitive type parameters
When a value of a primitive type is passed as a parameter, it is always copied. The parameter variable is initialised to a copy of the argument value. The argument value is computed in the method call:
obj.f(a + b);
Call-by-value
The parameter passing mechanism used by Java is called Call-by-value. This means that the value of a parameter is always copied and a parameter variable initialised with the copy. Objects are not passed as parameters, only references to objects.
The reference is copied.
Dont confuse references with a mechanism called pass-by-reference. Java does not support pass-by-reference.
The value is used to initialise the parameter variable of the called method: public void f(int n) { }
2006, Graham Roberts
37
2006, Graham Roberts
38
DEPARTMENT OF COMPUTER SCIENCE
DEPARTMENT OF COMPUTER SCIENCE
Variable is passed
Beware, this means the value held in the variable is passed as a parameter:
int x = 10; obj.f(x);
Return-by-value
Returning a value from a method works in the same way as parameter passing. public Person findPerson(String name) {
// find return aPerson;
The variable itself is not passed. The value of the variable is not changed by the method called.
But an object referenced by a variable of class type can change.
} The value returned is a copy of the value computed in the return statement.
2006, Graham Roberts
39
2006, Graham Roberts
40
DEPARTMENT OF COMPUTER SCIENCE
DEPARTMENT OF COMPUTER SCIENCE
Object lifetime
An object exists as long as it is accessible.
A reference to the object is available.
public Person makePerson() { ... // Get persons name Person newPerson = new Person(firstName,familyName); ... // Add some email addresses newPerson goes out of scope return newPerson; but object reference returned and object remains in existence. }
Summary
Seen how to construct a simple class. Methods and instance variables. Object references. References and parameter passing. Call-by-value, return-by-value. Object lifetime.
Use the method:
Person myPerson = makePerson();
Lifetime of reference variable different from lifetime of object.
2006, Graham Roberts
Object exists and is referenced by myPerson
41
2006, Graham Roberts
42