Object Oriented
Programming Techniques
1
Lecture 5: Classes
Paradigm shift
Procedural (or Imperative) Programming
Converting program specifications to method-
based code
Style of programming found in C, Pascal, Basic, …
Data and operations on data are separate
Object Oriented Programming
All the power of procedural programming… plus
some!
Supported by C++, C#, Java, Perl, Python, …
Data and operations on data are bundled together
in a structure called an Object
OOP: Lecture #8 Compiled By Umm-e-Laila 2
Classes
When working with objects, the first
thing to do is to create a blueprint of
the object…
An object is a specific instance of this
blueprint
The blueprint just describes how we
create objects
In Java, we call these blueprints
Classes
OOP: Lecture #8 Compiled By Umm-e-Laila 3
4 Classes
A class is a collection of fields (data) and methods (procedure or
function) that operate on that data.
Circle
centre
radius
circumference()
area()
5 Classes
A class is a collection of fields (data) and
methods (procedure or function) that operate
on that data.
The basic syntax for a class definition:
class ClassName [extends SuperClassName]
{
[fields declaration]
[methods declaration]
}
Bare bone class – no fields, no methods
public class Circle {
// my circle class
}
6 Adding Fields: Class
Circle with fields
Add fields
public class Circle {
public double x, y; // centre coordinate
public double r; // radius of the circle
The fields (data) are also called the instance varaibles.
7 Adding Methods
A class with only data fields has no life.
Objects created by such a class cannot
respond to any messages.
Methods are declared inside the body of
the class but immediately after the
declaration of data fields.
The general form of a method
declaration is:
type MethodName (parameter-list)
{
Method-body;
}
8 Adding Methods to Class
Circle
public class Circle {
public double x, y; // centre of the circle
public double r; // radius of circle
//Methods to return circumference and area
public double circumference() {
return 2*3.14*r;
}
public double area() {
return 3.14 * r * r;
}}
Method Body
9 Data Abstraction
Declare the Circle class, have created a new
data type – Data Abstraction
Can define variables (objects) of that type:
Circle aCircle;
Circle bCircle;
Alternative thinking
Programming in object oriented
languages is really just an alternative
way of thinking about problems
It’s a way of organising your code so
that the data and the operations on
that data are bundled together
Object types are just extended types…
There’s a hierarchy in OO code that
ultimately boils down to storing data in the
8 primitive data types but with methods to
go with them to mean that your extended
types are much more powerful
OOP: Lecture #8 Compiled By Umm-e-Laila 10
Object-oriented programming
So we’ve made our blueprint for Circle objects (though its not yet
complete…)
An object-oriented program can be viewed as a collection of
cooperating objects
Lets think about the data and operations of some other possible
objects
Circle — Data: radius; Operations: area, circumference…
Person class
Attributes: name, address, phone number
Methods: change address, change phone number
Alice object
Name is Alice, address is …
Bob object
Name is Bob, address is …
OOP: Lecture #8 Compiled By Umm-e-Laila 11
A Class as an Outline
12
Defining objects
Our Circle class isn’t quite ready yet…
You can only run a class if it has a main
method and even then you’re not
creating Objects!
The class we have tells Java what the
object looks like but it doesn’t tell Java
how to make a circle Object
The class variable, radius, doesn’t have
a default value so we need to find a
way to give it one
OOP: Lecture #8 Compiled By Umm-e-Laila 13
Constructor methods
A constructor method is a special
method that…
… has no return type (not even void!)
… has the same name as the class
public class Circle {
Object
// Its purpose
data is to set-up the object
according
double radius; to some rules
ForCircle(double
public our Circle class…
radius) {
this.radius = radius;
}
…
}
OOP: Lecture #8 Compiled By Umm-e-Laila 14
Constructor methods
public class Circle {
// Object data
double radius;
public Circle(double radius) {
this.radius = radius;
} We can have method variables with the same
…
}
name as class variables… However, if we
want to refer to the class variable, we must
prefix it with this.
This method will set the class variable to the value
of the parameter
A quick note on scope… it may seem like we’ve
used radius twice…
OOP: Lecture #8 Compiled By Umm-e-Laila 15
Creating objects
Now our Circle is complete we can start
using Circle objects
We’ve looked at arrays of monomorphic
data… Objects are a bit like arrays of
non-monomorphic data
They require a small amount of
contiguous memory to store all their
properties
To give them memory we use the new
keyword
OOP: Lecture #8 Compiled By Umm-e-Laila 16
Creating objects
With arrays, the new keyword just reserves enough
memory and sets default values
With objects, the new keyword reserves enough
memory and also calls the constructor function we
just wrote
The syntax is almost the same as for arrays
[ObjectType] variableName = new [ObjectType]([parameters]);
So to create one of our Circles…
Circle c = new Circle(0.5);
This will call the constructor method in the Circle
class with the radiusCompiled
OOP: Lecture #8
value of 0.5
By Umm-e-Laila 17
Creating objects
Lets create a new class to test our
public class CircleTest {
Circle
public staticout
void main(String[] args) {
CircleTest.java
Circle c = new Circle(0.5);
Circle c2 = new Circle(1.0);
System.out.println(“The area of c is: “ +
c.area());
System.out.println(“The circumference of c2 is:
” +
c2.circumference());
}
}
OOP: Lecture #8 Compiled By Umm-e-Laila 18
Creating objects
You don’t have to write a constructor
If you choose not to, Java will create a
default constructor
The default constructor does not set
any values so the object will do nothing
until you start interacting with it
Also, much like overloaded methods we
can write multiple different constructors
with different parameter lists
OOP: Lecture #8 Compiled By Umm-e-Laila 19
Differences between variables of
primitive
20 Data types and object types
Primitive type int i = 1 i 1
Object type Circle c c reference
c: Circle
Created using
new Circle() radius = 1
Copying Variables of Primitive
Data
21 Types and Object Types
Primitive type assignment Object type assignment
i=j c1 = c2
Before: After: Before: After:
i 1 i 2 c1 c1
j 2 j 2 c2 c2
c1: Circle c2: Circle
radius = 5 radius = 9
Passing Objects to Methods, cont.
22
main printAreas
method method
times
n 5 5 Pass by value (here the value is 5)
myCircle Reference Reference Pass by value (here the value is the
reference for the object)
myCircle: Circle
radius = 1
Array
23
of Objects
Circle[] circleArray = new Circle[10];
An array of objects is actually an array of
reference variables. So invoking
circleArray[1].findArea() involves two levels
of referencing as shown in the next figure.
circleArray references to the entire array.
circleArray[1] references to a Circle object.
Array
24
of Objects, cont.
Circle[] circleArray = new
Circle[10];
circleArray reference circleArray[0] Circle object 0
circleArray[1]
… Circle object 1
circleArray[9] Circle object 9
25 Automatic garbage
collection
If an object does not have a reference than that Object
cannot be used in future.
That object becomes a candidate for automatic garbage
collection.
Java automatically collects garbage periodically and
releases the memory used to be used in the future.
A note on comparisons…
All objects have an equals() method
The reason for this is that you can only
compare primitive types with ==
To compare two object types, we must
use:
Object o1 = new Object();
Object o2 = new Object();
if (o1.equals(o2)) {
// do something
}
OOP: Lecture #8 Compiled By Umm-e-Laila 26
Person
27
Class
------------ Person.java ------ defining ---------- PersonTest.java ----- using
Person Person --
public class Person
{
private String _name; public class PersonTest
private String _iceCream; {
public static void main(String[]
public void setName(String args)
newName) {
{ Person joe = new Person();
this._name = newName; // joe.setName(“Joseph”);
this. is optional joe.setIceCream(“Rocky
} Road”);
public void setIceCream(String
newIceCream) { … } Person mary = new Person();
mary.setName(“Mary”);
public void print() mary.setIceCream(“Chocolate
Fudge”);
{ System.out.println(this._nam mary.print(); }
The Point class
Lets look at the object that it returns…
Its a Point object! So lets look at the
Point blueprint (class!)
OOP: Lecture #8 Compiled By Umm-e-Laila 28
The Point class
The Point class has two properties…
OOP: Lecture #8 Compiled By Umm-e-Laila 29
The Point object
… And three constructor methods
OOP: Lecture #8 Compiled By Umm-e-Laila 30
The Point class
And it has a tonne of methods…
OOP: Lecture #8 Compiled By Umm-e-Laila 31
The Point class
…
Some of the methods are inherited
(more on this later!)
OOP: Lecture #8 Compiled By Umm-e-Laila 32
Exercise
So lets try to create our own Point class with a
subset of the methods in Java’s Point class…
We’ll start by creating the data
Then we’ll write methods for:
getting the X coordinate
getting the Y coordinate
moving the point
moving the point relative to its current position
writing the coordinates in a String
checking if the Point is equal to another point
OOP: Lecture #8 Compiled By Umm-e-Laila 33
Example
34
The Mortgage Class
Mortgage
-annualInterestRate: double
-numOfYears: int
-loanAmount: double
+Mortgage()
+Mortgage(annualInterestRate: double,
numOfYears: int, loanAmount: double)
+getAnnualInterestRate(): double
+getNumOfYears(): int
+getLoanAmount(): double
+setAnnualInterestRate(annualInteresteRate: double): void
+setNumOfYears(numOfYears: int): void
+setLoanAmount(loanAmount: double): void
+monthlyPayment(): double
+totalPayment(): double
Example
35 The Count Class
Summary
So now you should be able to:
Write an object specification (class)
Instantiate new instances of this class
Perform actions on its data