Lecture 5 Classes
Lecture 5 Classes
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
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]
}
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
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
ForCircle(double
public our Circle class…
radius) {
this.radius = radius;
}
…
}
c2.circumference());
}
}
c: Circle
Created using
new Circle() radius = 1
Copying Variables of Primitive
Data
21 Types and Object Types
i 1 i 2 c1 c1
j 2 j 2 c2 c2
radius = 5 radius = 9
Passing Objects to Methods, cont.
22
main printAreas
method method
times
myCircle: Circle
radius = 1
Array
23
of Objects
… Circle object 1
…
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