Slides 1
Slides 1
Slides 1
○ Study this tutorial video that walks you through the idea of
object orientation .
We observe how real-world entities behave.
○ We model the common attributes and behaviour of a set of
entities in a single class.
○ We execute the program by creating instances of classes, which
interact in a way analogous to that of real-world entities.
3 of 68
Object-Oriented Programming (OOP)
● In real life, lots of entities exist and interact with each other.
e.g., People gain/lose weight, marry/divorce, or get older.
e.g., Cars move from one point to another.
e.g., Clients initiate transactions with banks.
● Entities:
Possess attributes;
○ Exhibit bebaviour ;and
○ Interact with each other.
● Goals: Solve problems programmatically by
○ Classifying entities of interest
Entities in the same class share common attributes and bebaviour.
○ Manipulating data that represent these entities
Each entity is represented by specific values.
4 of 68
OO Thinking: Templates vs. Instances (1.1)
5 of 68
OO Thinking: Templates vs. Instances (1.2)
6 of 68
OO Thinking: Templates vs. Instances (2.1)
7 of 68
OO Thinking: Templates vs. Instances (2.2)
8 of 68
OO Thinking: Templates vs. Instances (3)
● A template defines what’s shared by a set of related entities.
Common attributes (age in Person, x in Point)
○ Common behaviour (get older for Person, move up for Point)
● Each template may be instantiated into multiple instances.
○ Person instances: jim and jonathan
○ Point instances: p1 and p2
● Each instance may have specific values for the attributes.
○ Each Person instance has an age:
jim is 50-years old, jonathan is 65-years old
○ Each Point instance has a location:
p1 is at (3, 4), p2 is at (−3,−4)
● Therefore, instances of the same template may exhibit distinct
behaviour.
○ Each Person instance can get older: jim getting older from 50 to
51; jonathan getting older from 65 to 66.
○ Each Point instance can move up: p1 moving up from (3, 3)
9 of 68
results in (3, 4 ); p1 moving up from (−3, −4 )results in (−3,
−)3 .
OOP: Classes ≈ Templates
publicclass Point {
double x;
double y;
}
10 of 68
OOP:
Define Constructors for Creating Objects (1.1)
● Within class Point, you define constructors , specifying how
instances of the Point template may be created.
publicclass Point {
. . . /* attributes:x,y */
Point(double newX,double newY) {
x = newX;
y = newY; } }
y 4.0
Person
age 50
nationality “British”
weight 80
height 1.8
16 of 68
Visualizing Objects at Runtime (2.2)
After calling an accessor to inquire about context object jim:
double bmi = jim.getBMI();
Person
age 50
nationality “British”
weight 80
height 1.8
17 of 68
Visualizing Objects at Runtime (2.3)
After calling a mutator to modify the state of context object jim:
jim.gainWeightBy(10);
Person
age 50
nationality “British”
weight 80 90
height 1.8
18 of 68
Visualizing Objects at Runtime (2.4)
After calling the same accessor to inquire the modified state of
context object jim:
bmi = p.getBMI();
Person
age 50
nationality “British”
weight 80 90
height 1.8
19 of 68
The this Reference (1)
● Each class may be instantiated to multiple objects at runtime.
class Point {
double x;double y;
void moveUp(double units) { y += units; }
}
Why? Fix?
25 of 68
The this Reference (6.2): Common Error
26 of 68
OOP: Methods (1.1)
●A method is a named block of code, reusable via its name.
m
T1 p1
{
T2 p2 …
RT
… /* implementation of method m */
}
Tn pn
● The header of a method consists of: [see here]
○ Return type [ RT (which can be void)]
Name of method [ m]
○ Zero or more parameter names [ p1, p2, . . . ,pn ]
○ The corresponding parameter types [ T1, T2, . . ., Tn ]
● A call to method m has the form: m(a1 , a2 , . . . , a n)
Types of argument valuesa 1, a2, . . . , an must match thethe
corresponding parameter types T1, T2, . . . , Tn.
27 of 68
OOP: Methods (1.2)
● Inthe body of the method, you may
○ Declare and use new localvariables
Scope of local variables is only within that method.
Use or change values ofattributes.
○ Use values of parameters, if any.
class Person {
String nationality;
void changeNationality(String newNationality ) {
nationality = newNationality ; } }
A binary operator:
LHS stores an address (which denotes an object)
○RHS the name of an attribute or a method
○ LHS . RHS means:
Locate the context object whose address is stored in LHS,
then apply RHS.
What if LHS stores null? [ NullPointerException ]
31 of 68
OOP: The Dot Notation (1.2)
32 of 68
OOP: Method Calls
1 Point p1 =new Point (3, 4);
2 Point p2 =new Point (-6, -8);
3 System.out.println(p1. getDistanceFromOrigin() );
4 System.out.println(p2. getDistanceFromOrigin() );
5 p1. moveUp(2) ;
6 p2. moveUp(2) ;
7 System.out.println(p1. getDistanceFromOrigin() );
8 System.out.println(p2. getDistanceFromOrigin() );
34 of 68
OOP: Class Constructors (2)
publicclass Person {
int age;
String nationality;
double weight;
double height;
Person(int initAge,String initNat) {
age = initAge;
nationality = initNat;
}
Person (double initW,double initH) {
weight = initW;
height = initH;
}
Person(int initAge,String initNat,
double initW,double initH) {
. . . /* initializeallattributesusingtheparameters */
}
}
35 of 68
OOP: Class Constructors (3)
publicclass Point {
double x;
double y;
36 of 68
OOP: Class Constructors (4)
37 of 68
OOP: Object Creation (1)
Point@677327b6
(2.0, 4.0)
38 of 68
OOP: Object Creation (2)
A constructor may only initialize some attributes and leave others
uninitialized.
publicclass PersonTester {
publicstaticvoid main(String[] args) {
/* initializeageandnationalityonly */
Person jim =new Person(50, "BRI");
/* initializeageandnationalityonly */
Person jonathan =new Person(65, "CAN");
/* initializeweightandheightonly */
Person alan =new Person(75, 1.80);
/* initializeallattributesofaperson */
Person mark =new Person(40, "CAN", 69, 1.78);
}
}
39 of 68
OOP: Object Creation (3)
40 of 68
OOP: Object Creation (4)
publicclass PointTester {
publicstaticvoid main(String[] args) {
Point p1 =new Point(3, 4);
Point p2 =new Point(-3 -2);
Point p3 =new Point(’x’, 5);
Point p4 =new Point(’y’, -7);
}
}
41 of 68
OOP: Object Creation (5)
Person Person
x 3.0 x -3.0
p1 y p2 y -2.0
4.0
Point p3 = new Point(‘x’, 5) Point p4 = new Point(‘y’, -7)
Person Person
x 5.0 x 0
p3 p4 y -7.0
y 0
42 of 68
OOP: Object Creation (6)
43 of 68
OOP: Mutator Methods
These methods change values of attributes.
● We call such methods mutators (with void return type).
publicclass Person {
...
void gainWeight(double units) {
weight = weight + units;
}
}
publicclass Point {
...
void moveUp() {
y = y + 1;
}
}
44 of 68
OOP: Accessor Methods
● These methods return the result of computation based on
attribute values.
● We call such methods accessors (with non-void return type).
publicclass Person {
...
double getBMI() {
double bmi = height / (weight * weight);
return bmi;
}
}
publicclass Point {
...
double getDistanceFromOrigin() {
double dist = Math.sqrt(x*x + y*y);
return dist;
}
45 o}f68
OOP: Use of Mutator vs. Accessor Methods
46 of 68
OOP: Method Parameters
● Principle 1: A constructor needs an input parameter for
every attribute that you wish to initialize.
e.g., Person(double w, double h) vs.
Person(String fName, String lName)
● Principle 2: A mutator method needs an input parameter for
every attribute that you wish to modify.
e.g., In Point, void moveToXAxis() vs.
void moveUpBy(double unit)
● Principle 3: An accessor method needs input parameters if
the attributes alone are not sufficient for the intended
computation to complete.
e.g., In Point, double getDistFromOrigin() vs.
double getDistFrom(Point other)
47 of 68
OOP: Object Alias (1)
1 int i = 3;
2 int j = i; System.out.println(i == j); /* true */
3 int k = 3; System.out.println(k == i && k == j); /* true */
49 of 68
OO Program Programming: Object Alias (2.2)
Problem: Consider assignments to reference variables:
1 Person alan =new Person("Alan");
2 Person mark =new Person("Mark");
3 Person tom =new Person("Tom");
4 Person jim =new Person("Jim");
5 Person[] persons1 = {alan, mark, tom};
6 Person[] persons2 =new Person[persons1.length];
7 for(int i = 0; i < persons1.length; i ++) {
8 persons2[i] = persons1[(i + 1) % persons1.length]; }
9 persons1[0].setAge(70);
10 System.out.println(jim.age); /* 0 */
11 System.out.println(alan.age); /* 70 */
12 System.out.println(persons2[0].age); /* 0 */
13 persons1[0] = jim;
14 persons1[0].setAge(75);
15 System.out.println(jim.age); /* 75 */
16 System.out.println(alan.age); /* 70 */
17 System.out.println(persons2[0].age); /* 0 */
50 of 68
OO Program Programming: Object Alias (3)
Person tom =new Person("TomCruise");
Person ethanHunt = tom;
Person spy = ethanHunt;
tom.setWeight(77);print(tom.weight); /* 77 */
ethanHunt.gainWeight(10); print(tom.weight); /* 87 */
spy.loseWeight(10); print(tom.weight); /* 77 */
Person prof =new Person("Jackie"); prof.setWeight(80);
spy = prof ; prof = tom ; tom = spy ;
print(prof.name+" teaches 2030");/*TomCruiseteaches2030 */
print("EthanHunt is "+ethanHunt.name);/*EthanHuntisTomCruise *
print("EthanHunt is "+spy.name);/*EthanHuntisJackie */
print("TomCruise is "+tom.name);/*TomCruiseisJackie */
print("Jackie is "+prof.name);/*JackieisTomCruise */
54 of 68
Java Data Types (1)
A (data) type denotes a set of related runtimevalues.
1. Primitive Types
○ Integer Type
int [set of 32-bit integers]
● long [set of 64-bit integers]
○ Floating-Point Number Type
○ ● double [set of 64-bit FP numbers]
Character Type
● char [set of single characters]
○ Boolean● Type
2. Reference Type : Complex Type with Attributes
boolean [set ofand Methods
true and false]
class Account {
int id;
String owner;
Account(int id,String owner) {
this.id = id;
this.owner = owner;
}
}
class AccountTester {
Account acc1 =new Account(1, "Jim");
Account acc2 =new Account(2, "Jeremy");
System.out.println(acc1.id != acc2.id);
}
class AccountTester {
Account acc1 =new Account("Jim");
Account acc2 =new Account("Jeremy");
System.out.println(acc1.id != acc2.id); }
class ClientTester {
Client bill =new Client("Bill");
Client steve =new Client("Steve");
Account acc1 =new Account();
Account acc2 =new Account();
bill.addAccount(acc1);
/* correctlyaddedtobill.accounts[0] */
steve.addAccount(acc2);
/* mistakenlyaddedtosteve.accounts[1]! */
}
63 of 68
Static Variables (4.2): Common Error
● Attribute numberOfAccounts should not be declared as
static as its value should be specific to the client object.
● If it were declared as static, then every time the
addAccount method is called, although on different objects,
the increment effect of numberOfAccounts will be visibleto
all Client objects.
● Here is the correct version:
class Client {
Account[] accounts;
int numberOfAccounts = 0;
void addAccount(Account acc) {
accounts[numberOfAccounts] = acc;
numberOfAccounts ++;
}
}
64 of 68
Static Variables (5.1): Common Error
1 publicclass Bank {
2 publicstring branchName;
3 publicstaticint nextAccountNumber = 1;
4 publicstaticvoid useAccountNumber() {
5 System.out.println (branchName + . . .);
6 nextAccountNumber ++;
7 }
8 }
67 of 68
Index(1)
Separation of Concerns: App/Tester vs. Model
Object Orientation:
Observe, Model, and Execute
Object-Oriented Programming (OOP)
OO Thinking: Templates vs. Instances (1.1)
OO Thinking: Templates vs. Instances (1.2)
OO Thinking: Templates vs. Instances (2.1)
OO Thinking: Templates vs. Instances (2.2)
OO Thinking: Templates vs. Instances (3)
OOP: Classes ≈Templates
OOP:
Define Constructors for Creating Objects (1.1)
OOP:
Define Constructors for Creating Objects (1.2)
68 of 68
Index(2)
OOP:
Define Constructors for Creating Objects (2.1)
OOP:
Define Constructors for Creating Objects (2.2)
Visualizing Objects at Runtime (1)
Visualizing Objects at Runtime (2.1)
Visualizing Objects at Runtime (2.2)
Visualizing Objects at Runtime (2.3)
Visualizing Objects at Runtime (2.4)
The this Reference (1)
The this Reference (2)
The this Reference (3)
The this Reference (4)
The this Reference (5)
69 of 68
Index(3)
The this Reference (6.1): Common Error
The this Reference (6.2): Common Error
OOP: Methods (1.1)
OOP: Methods (1.2)
OOP: Methods (2)
OOP: Methods (3)
OOP: The Dot Notation (1.1)
OOP: The Dot Notation (1.2)
OOP: Method Calls
OOP: Class Constructors (1)
OOP: Class Constructors (2)
OOP: Class Constructors (3)
OOP: Class Constructors (4)
OOP: Object Creation (1)
70 of 68
Index(4)
OOP: Object Creation (2)
OOP: Object Creation (3)
OOP: Object Creation (4)
OOP: Object Creation (5)
OOP: Object Creation (6)
OOP: Mutator Methods
OOP: Accessor Methods
OOP: Use of Mutator vs. Accessor Methods
OOP: Method Parameters
OOP: Object Alias (1)
OOP: Object Alias (2.1)
OOP: Object Alias (2.2)
OOP: Object Alias (3)
Anonymous Objects (1)
71 of 68
Index(5)
Anonymous Objects (2.1)
Anonymous Objects (2.2)
Java Data Types (1)
Java Data Types (2)
Java Data Types (3.1)
Java Data Types (3.2.1)
Java Data Types (3.2.2)
Static Variables (1)
Static Variables (2)
Static Variables (3)
Static Variables (4.1): Common Error
Static Variables (4.2): Common Error
Static Variables (5.1): Common Error
Static Variables (5.2): Common Error
72 of 68
Index(6)
Static Variables (5.3): Common Error
73 of 68