3 (3,4,5) Encapsulation
3 (3,4,5) Encapsulation
Unit 4. Encapsulation
Objectives
Programming model and OOP
• Using object-oriented modeling to formulate
solution
[CMP167-Unit 4-Encapsulation]
2
Outline (1/2)
1. Recapitulation
2. Programming Model and OOP
2.1 Procedural vs OOP
2.2 Illustration: Bank Account
3. OOP Design
3.1 Designing Own Classes
3.2 Bank Account: BankAcct class
3.3 Accessors and Mutators
3.4 Writing Client Class
[501043
[CMP167-Unit
Lecture
4-Encapsulation]
3: OOP Part 2]
3
Outline (2/2)
4. More OOP Concepts
4.1 Class and Instance members
4.2 MyBall class: Draft
4.3 “this” reference
4.4 Using “this” in Constructors
4.5 Overriding Methods: toString() and equals()
4.6 MyBall class: Improved
5. Unified Modeling Language (UML)
6. Exercises
[501043
[CMP167-Unit
Lecture
4-Encapsulation]
3: OOP Part 2]
4
1. Recapitulation
◼ We revisited a few classes (Scanner, String,
Math) and learnt a few new ones (DecimalFormat,
Random)
◼ Last week, we used classes provided by API as a
user.
◼ Today, we become designers to create our own
classes!
[501043
[CMP167-Unit
Lecture
4-Encapsulation]
3: OOP Part 2]
5
2. Programming Model and
OOP
[501043
[CMP167-Unit
Lecture
4-Encapsulation]
3: OOP Part 2]
7
2. Prog. Model Hello World!
Pascal
Program HelloWorld;
Begin
WriteLn('Hello World!');
End.
Java
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World!");
}
}
Prolog
go :-
writeln('Hello World!').
[501043
[CMP167-Unit
Lecture
4-Encapsulation]
3: OOP Part 2]
8
2. Prog. Model Procedural (eg: C) versus OOP (eg: Java)
Procedural/Imperative OOP
• View program as a process of • Encapsulation (tính
transforming data đóng gói)
• Inheritance (tính kế
• Data and associated functions are thừa)
separated • Abstraction (tính trừu
tượng)
• Data is publicly accessible to
everyone • Polymorphism (tính
đa hình)
Advantages Disadvantages
• Resembles • Harder to understand as
execution model logical relation between data
of computer and functions is unclear
• Less overhead • Hard to maintain
when designing • Hard to extend/expand
[501043
[CMP167-Unit
Lecture
4-Encapsulation]
3: OOP Part 2]
9
2. Prog. Model OOP
4 fundamental OOP concepts
• Encapsulation Today’s
• Bundling data and associated functionalities
focus
• Hide internal details and restricting access
• Inheritance
• Deriving a class from another, affording code reuse
• Abstraction
• Hiding the complexity of the implementation
• Focusing on the specifications and not the implementation
details
• Polymorphism
• Behavior of functionality changes according to the actual
type of data
[501043
[CMP167-Unit
Lecture
4-Encapsulation]
3: OOP Part 2]
10
2. Prog. Model Illustration: Bank Account
◼ (Note: This illustration serves as a quick comparison between a
procedural language and an object-oriented language; it is not
meant to be comprehensive.)
Data Operations
[501043
[CMP167-Unit
Lecture
4-Encapsulation]
3: OOP Part 2]
11
2. Prog. Model Bank Account (C implementation) (1/4)
typedef struct {
Structure to
int acctNum;
double balance;
hold data
} BankAcct;
Passed
into
Data Function
BankAcct deposit(..)
Modifies withdraw(…)
structure
[501043
[CMP167-Unit
Lecture
4-Encapsulation]
3: OOP Part 2]
13
2. Prog. Model Bank Account (C implementation) (3/4)
Forgot to initialize
BankAcct ba1;
Wrong and
malicious deposit(&ba1, 1000.50); Account Number
exploits of should not change!
BankAcct initialize(&ba1, 12345);
ba1.acctNum = 54321; Balance should be
changed by
ba1.balance = 10000000.00; authorized
... operations only
[501043
[CMP167-Unit
Lecture
4-Encapsulation]
3: OOP Part 2]
14
2. Prog. Model Bank Account (C implementation) (4/4)
◼ Characteristics of a procedural language
❑ View program as a process of transforming
data
❑ Data and associated functions are separated
◼ Requires good programming discipline to ensure
good organization in a program
❑ Data is publicly accessible to everyone (!)
◼ Potentially vulnerable to unauthorised or
uncontrolled access/modification
[501043
[CMP167-Unit
Lecture
4-Encapsulation]
3: OOP Part 2]
15
2. Prog. Model Bank Account (OO implementation) (1/2)
◼ Characteristics of an OOP language
❑ View program as a collection of objects
◼ Computation is performed through interaction with
the objects
❑ Each object has data attributes and a set of
functionalities (behaviours)
◼ Functionalities are generally exposed to the
public…
◼ While data attributes are generally kept within the
object, hidden from and inaccessible to the public
[501043
[CMP167-Unit
Lecture
4-Encapsulation]
3: OOP Part 2]
16
2. Prog. Model Bank Account (OO implementation) (2/2)
◼ A conceptual view of an OO implementation for
Bank Account
Call method to
Methods manipulate object
BankAcct
object
Encapsulation of
Data
data and methods No direct
access to
data
[501043
[CMP167-Unit
Lecture
4-Encapsulation]
3: OOP Part 2]
17
2. Prog. Model Procedural (eg: C) versus OOP (eg: Java)
Procedural/Imperative OOP
• View program as a process of • Encapsulation
transforming data
• Inheritance
• Data and associated functions are
• Abstraction
separated
• Polymorphism
• Data is publicly accessible to
everyone
[501043
[CMP167-Unit
Lecture
4-Encapsulation]
3: OOP Part 2]
18
3. OOP Design
[501043
[CMP167-Unit
Lecture
4-Encapsulation]
3: OOP Part 2]
21
3. OOP Design Designing Own Classes (3/7)
◼ What is the purpose of a (service) class?
A template to create
instances (objects) out of it.
[501043
[CMP167-Unit
Lecture
4-Encapsulation]
3: OOP Part 2]
24
3. OOP Design Designing Own Classes (6/7)
◼ Some general guidelines...
◼ Attributes are usually private
❑ Information hiding, to shield data of an object from outside view
❑ Instead, we provide public methods for user to access the
attributes through the public methods
❑ There are exceptions. Example: Point class has public
attributes x and y, most likely due to legacy reason.
◼ Methods are usually public
❑ So that they are available for users
◼ Imagine that the methods in String class and Math class are
private instead, then we cannot even use them!
❑ If the methods are to be used internally in the service
class itself and not for users, then the methods should be
declared private instead
[501043
[CMP167-Unit
Lecture
4-Encapsulation]
3: OOP Part 2]
25
Bank Account: BankAcct Class (1/2)
BankAcct.java
3. OOP Design
class BankAcct {
private int acctNum;
private double balance; Attributes of BankAcct
// Default constructor
public BankAcct() {
// By default, numeric attributes
Constructors:
// are initialised to 0
Name must be
}
identical to
class name.
public BankAcct(int aNum, double bal) {
No return type.
// Initilize attributes with user
// provided values
Can be
acctNum = aNum;
overloaded.
balance = bal;
}
[501043
[CMP167-Unit
Lecture
4-Encapsulation]
3: OOP Part 2]
26
Bank Account: BankAcct Class (2/2)
BankAcct.java
3. OOP Design
[501043
[CMP167-Unit
Lecture
4-Encapsulation]
3: OOP Part 2]
27
3. OOP Design Accessors and Mutators
◼ Note that for service class, we use the default visibility for
the class (i.e. no modifier before the class name)
◼ Besides constructors, there are two other types of special
methods that can be referred to as accessors (phương
thức truy cập) and mutators (phương thức thay đổi).
◼ An accessor is a method that accesses (retrieves) the
value of an object’s attribute
❑ Eg: getAcctNum(), getBalance()
❑ Its return type must match the type of the attribute it retrieves
◼ A mutator is a method that mutates (modifies) the
value of an object’s attribute
❑ Eg: withdraw(), deposit()
❑ Its return type is usually void, and it usually takes in some
argument to modify the value of an attribute
[501043
[CMP167-Unit
Lecture
4-Encapsulation]
3: OOP Part 2]
28
3. OOP Design Designing Own Classes (7/7)
◼ As a (service) class designer, you decide the
following:
❑ What attributes you want the class to have
❑ What methods you want to provide for the class so that
users may find them useful
❑ For example, the print() method is provided for BankAcct
as the designer feels that it might be useful. Or, add a
transfer() method to transfer money between 2 accounts?
◼ As in any design undertaking, there are no hard and
fast rules. One approach is to study the classes in
the API documentation to learn how others
designed the classes, and google to explore.
◼ You need to practise a lot and ask questions.
[501043
[CMP167-Unit
Lecture
4-Encapsulation]
3: OOP Part 2]
29
3. OOP Design Writing Client Class – User Mode
◼ Note that there is no main() method in BankAcct class
because it is a service class, not a client class
(application program). You cannot execute BankAcct.
◼ So how do we write a client class to make use of
BankAcct?
◼ You have written a number of client classes in the past
weeks. These classes contain the main() method.
◼ In general, the service class and the client class may
be put into a single .java program, mostly for quick
testing. (However, there can only be 1 public class in such a
program, and the public class name must be identical to the
program name.)
◼ We will write 1 class per .java program here (most of
the time) to avoid confusion.
[501043
[CMP167-Unit
Lecture
4-Encapsulation]
3: OOP Part 2]
30
Client Class: TestBankAcct
TestBankAcct.java
3. OOP Design
public class TestBankAcct {
public static void main(String[] args) { Which constructor
BankAcct ba1 = new BankAcct(); is used?
BankAcct ba2 = new BankAcct(1234, 321.70);
System.out.println("Before transactions:");
ba1.print();
ba2.print();
ba1.deposit(1000);
ba1.withdraw(200.50);
ba2.withdraw(500.25);
System.out.println();
System.out.println("After transactions:");
ba1.print();
ba2.print();
}
}
[501043
[CMP167-Unit
Lecture
4-Encapsulation]
3: OOP Part 2]
31
3. OOP Design What happens if…
public class TestBankAcct {
public static void main(String[] args) {
BankAcct ba1 = new BankAcct();
/* Instead of
ba1.deposit(1000);
*/
ba1.balance += 1000;
}
} Compilation error!
balance has private access in BankAcct
[501043
[CMP167-Unit
Lecture
4-Encapsulation]
3: OOP Part 2]
32
3. OOP Design Compiling Classes
◼ BankAcct.java and TestBankAcct.java can be compiled
independently.
◼ Only TestBackAcct class can be executed.
javac BankAcct.java
javac TestBankAcct.java
java TestBankAcct
◼ We say TestBankAcct uses or depends on BankAcct.
◼ We can write many clients that depend on the same
service class. (Eg: Many client programs you have seen
depend on the Scanner service class.)
◼ Likewise, a client may also depend on more than one
service class. (Eg: TestMath in lecture #1 depends on both
Scanner and Math service classes.)
[501043
[CMP167-Unit
Lecture
4-Encapsulation]
3: OOP Part 2]
33
Exercise
◼ Writing the Student Class with
◼ Solution:
34
4. More OOP Concepts
4. More OOP Concepts Class and Instance members
◼ A class comprises 2 types of members: attributes (data
members) and methods (behaviour members)
◼ Java provides the modifier static to indicate if the
member is a class member or an instance member
Attribute Method
Class Class
static
attribute method
Instance Instance
default
attribute method
[501043
[CMP167-Unit
Lecture
4-Encapsulation]
3: OOP Part 2]
36
4. More OOP Concepts Designing MyBall Class (1/2)
◼ Let’s create a new class called MyBall
❑ Obviously, we want to create ball objects out of it
[501043
[CMP167-Unit
Lecture
4-Encapsulation]
3: OOP Part 2]
37
4. More OOP Concepts Designing MyBall Class (2/2)
◼ Sometimes, we want to have some class attributes in a
class, shared by all instances (objects) of that class
◼ Let’s have one class attribute for illustration purpose
❑ The number of Myball objects created in a program run
◼ Next, for behaviours, a class in general consists of at
least these 3 types of methods
❑ Constructors: to create an instance. Usually there are
overloaded constructors. Default constructor has no parameter,
and is automatically provided by the compiler if there is no
constructor present in the class, and all numeric attributes are
initialised to 0 and object attributes initialised to NULL.
❑ Accessors: to access (retrieve) values of the attributes
❑ Mutators: to mutate (modify) values of the attributes
[501043
[CMP167-Unit
Lecture
4-Encapsulation]
3: OOP Part 2]
38
MyBall Class: Draft (1/2)
MyBall_draft/MyBall.java
4. More OOP Concepts
class MyBall { MyBall.java
/************** Data members **********************/
private static int quantity = 0;
private String colour;
private double radius;
[501043
[CMP167-Unit
Lecture
4-Encapsulation]
3: OOP Part 2]
39
MyBall Class: Draft (2/2)
MyBall_draft/MyBall.java
4. More OOP Concepts
[501043
[CMP167-Unit
Lecture
4-Encapsulation]
3: OOP Part 2]
40
Testing MyBall: TestBallV1 (1/2)
MyBall_draft/TestBallV1.java
4. More OOP Concepts
import java.util.*;
public lass TestBallV1 {
public static void main(String[] args) {
String inputColour;
double inputRadius;
Scanner sc = new Scanner(System.in);
[501043
[CMP167-Unit
Lecture
4-Encapsulation]
3: OOP Part 2]
41
Testing MyBall: TestBallV1 (2/2)
4. More OOP Concepts
import java.util.*;
public class TestBallV1 { Enter colour: red
public static void main(String[] args) { Enter radius: 1.2
String inputColour;
double inputRadius;
Enter colour: blue
Scanner sc = new Scanner(System.in);
Enter radius: 3.5
// Read ball's input and create a ball object
System.out.print("Enter colour: "); inputColour = sc.next();
System.out.print("Enter radius: "); inputRadius = sc.nextDouble();
MyBall myBall1 = new MyBall(inputColour, inputRadius);
System.out.println();
◼ You may have noticed that the codes for reading and
construction a MyBall object are duplicated in
TestBallV1.java
◼ We can modularise the program by creating a method
readBall() to perform this task, which can then be
called as many times as necessary
◼ We name this modified program TestBallV2.java,
shown in the next slide
◼ Changes in the client program do not affect the
services defined in the service class MyBall
[501043
[CMP167-Unit
Lecture
4-Encapsulation]
3: OOP Part 2]
43
Testing MyBall: TestBallV2
import java.util.*; MyBall_draft/TestBallV2.java
4. More OOP Concepts
[501043
[CMP167-Unit
Lecture
4-Encapsulation]
3: OOP Part 2]
45
“this” reference (2/4)
// b1 and b2 are MyBall objects
4. More OOP Concepts
b1.setColour("purple");
b2.setColour("brown");
◼ A common confusion:
❑ How does the method “know” which is
the “object” it is currently communicating
with? (Since there could be many b1 colour
objects created from that class.) "purple"
this radius
◼ Whenever a method is called,
❑ a reference to the calling object is set
automatically b2 colour
/* Mutators */
public void setColour(String colour) {
this.colour = colour;
✓
} parameters
attributes
public void setRadius(double radius) {
this.radius = radius;
}
[501043
[CMP167-Unit
Lecture
4-Encapsulation]
3: OOP Part 2]
47
4. More OOP Concepts “this” reference (4/4)
◼ The “this” is optional for unambiguous (rõ ràng) case
Optional
public String getColour() { return this.colour; }
[501043
[CMP167-Unit
Lecture
4-Encapsulation]
3: OOP Part 2]
48
Naming Convention for Attributes
Some suggested that object’s attributes be named
4. More OOP Concepts
◼
with a prefix “_” (or “m_”) or a suffice “_” to distinguish
them from other variables/parameters.
◼ This would avoid the need of using “this” as there
would be no ambiguity
class MyBall {
/******** Data members **********/
private static int _quantity = 0;
private String _colour;
private double _radius;
. . .
}
[501043
[CMP167-Unit
Lecture
4-Encapsulation]
3: OOP Part 2]
51
Using “this” in Constructors (2/2)
To reuse code, we can use “this” in a constructor to call
4. More OOP Concepts
◼
another constructor:
Restriction: Call to “this”
public MyBall() {
this("yellow", 10.0);
must be the first statement
} in a constructor.
◼
radius) of a MyBall object.
◼ Suppose we print a MyBall object as a whole unit in TestBallV3.java:
import java.util.*;
MyBall_draft/TestBallV3.java
public class TestBallV3 {
// readBall() method omitted
[501043
[CMP167-Unit
Lecture
4-Encapsulation]
3: OOP Part 2]
54
4. More OOP Concepts Printing an Object: toString() (3/3)
◼ After toString() method is added in MyBall.java,
a client program can use it in either of these
ways:
System.out.println(myBall1);
System.out.println(myBall1.toString());
[501043
[CMP167-Unit
Lecture
4-Encapsulation]
3: OOP Part 2]
55
4. More OOP Concepts Object class and inherited methods (1/2)
◼ Why did we call the preceding method toString() and not
by other name?
◼ All Java classes are implicitly subclasses of the class
Object
◼ Object class specifies some basic behaviours common
to all kinds of objects, and hence these behaviours are
inherited by its subclasses
◼ Some inherited methods from the Object class are:
❑ toString() method: to provide a string representation of the
object’s data
❑ equals() method: to compare two objects to see if they contain
identical data
◼ However, these inherited methods (phương pháp kế
thừa) usually don’t work (!) as they are not customised
[501043
[CMP167-Unit
Lecture
4-Encapsulation]
3: OOP Part 2]
56
4. More OOP Concepts Object class and inherited methods (2/2)
◼ Hence, we often (almost always) need to customise
these inherited methods for our own class
◼ This is called overriding
◼ We have earlier written an overriding method toString()
for MyBall class
◼ We shall now write an overriding method equals() for
MyBall class
◼ The equals() method in Object class has the following
header, hence our overriding method must follow the
same header: (if we don’t then it is not overriding)
public boolean equals(Object obj)
[501043
[CMP167-Unit
Lecture
4-Encapsulation]
3: OOP Part 2]
57
4. More OOP Concepts Comparing objects: equals() (1/2)
◼ To compare if two objects have the same data values,
we should use equals() instead of ==
◼ == compares the references of the objects instead
MyBall/TestEquals.java
colour
MyBall b1, b2, b3; b1
NULL "red"
b1 = new MyBall("red", 6.2);
b2 = b1; radius
b3 = new MyBall("red", 6.2); b2
NULL
6.2
True or false?
b3
(b1 == b2) → NULL
colour
(b1 == b3) → "red"
b1.equals(b2) → radius
b1.equals(b3) → 6.2
[501043
[CMP167-Unit
Lecture
4-Encapsulation]
3: OOP Part 2]
58
4. More OOP Concepts Comparing objects: equals() (2/2)
◼ Code for equals() method
❑ It compares the colour and radius of both objects (“this” and
ball, which is the ‘equivalent’ of the parameter obj)
MyBall/MyBall.java
class MyBall {
// Other parts omitted instanceof: To check that the parameter
obj is indeed a MyBall object
// Overriding equals() method
public boolean equals(Object obj) {
if (obj instanceof MyBall) {
MyBall ball = (MyBall) obj;
return this.getColour().equals(ball.getColour())
&& this.getRadius() == ball.getRadius();
} Made a local reference ball of class
else MyBall so that getColour() and
return false; getRadius() can be applied on it,
} because obj is an Object instance,
} not a MyBall instance.
[501043
[CMP167-Unit
Lecture
4-Encapsulation]
3: OOP Part 2]
59
MyBall Class: Improved (1/2)
We apply more OOP concepts to our draft MyBall class: “this”
4. More OOP Concepts
◼
reference, “this” in constructor, overriding methods toString() and
equals()
MyBall/MyBall.java
class MyBall {
/************** Data members **********************/
private static int quantity = 0;
private String colour;
private double radius;
/************** Constructors **********************/
public MyBall() {
this("yellow", 10.0);
}
public MyBall(String colour, double radius) {
setColour(colour);
setRadius(radius);
quantity++; “this” is
} optional here.
/**************** Accessors ***********************/
public static int getQuantity() { return quantity; }
public String getColour() { return this.colour; }
public double getRadius() { return this.radius; }
[501043
[CMP167-Unit
Lecture
4-Encapsulation]
3: OOP Part 2]
60
MyBall Class: Improved (2/2)
MyBall/MyBall.java
4. More OOP Concepts
/**************** Mutators ************************/
public void setColour(String colour) {
this.colour = colour; “this” is
} required here.
public void setRadius(double radius) {
this.radius = radius;
}
/***************** Overriding methods ******************/
// Overriding toString() method
public String toString() {
return "[" + getColour() + ", " + getRadius() + "]";
}
// Overriding equals() method
public boolean equals(Object obj) {
if (obj instanceof MyBall) {
MyBall ball = (MyBall) obj;
return this.getColour().equals(ball.getColour()) &&
this.getRadius() == ball.getRadius();
}
else
return false;
}
}
[501043
[CMP167-Unit
Lecture
4-Encapsulation]
3: OOP Part 2]
61
4. More OOP Concepts Final client program: TestBallV4 (1/2)
◼ With the overriding methods toString() and equals() added to the
MyBall class, the final client program TestBallV4.java is shown here
(some part of the code not shown here due to space constraint)
import java.util.*; MyBall/TestBallV4.java
public class TestBallV4 {
// readBall() method omitted for brevity
[501043
[CMP167-Unit
Lecture
4-Encapsulation]
3: OOP Part 2]
62
4. More OOP Concepts Final client program: TestBallV4 (2/2)
◼ Sample run
Enter colour: red
Enter radius: 1.2
Enter colour: red
Enter radius: 1.2
[501043
[CMP167-Unit
Lecture
4-Encapsulation]
3: OOP Part 2]
63
5. Unified Modeling Language
(UML)
Methods
For attributes:
SYNTAX
For methods:
[visibility] method(para: data_type): return_type
MyBall
- quantity: int ▪ Underlined
- Colour: String attributes/methods indicate
- radius: double class attributes/methods
+ MyBall() ▪ Otherwise, they are
+ MyBall(newColour: String, instance attributes/methods
newRadius: double)
+ getQuantity(): int
+ getColour(): String
+ getRadius(): double
+ setColour(newColour: String)
+ setRadius(newRadius: double)
[501043
[CMP167-Unit
Lecture
4-Encapsulation]
3: OOP Part 2]
67
5 UML UML Diagrams (1/3)
Examples
<Class Name> MyBall
A class
[501043
[CMP167-Unit
Lecture
4-Encapsulation]
3: OOP Part 2]
68
5 UML UML Diagrams (2/3)
Example
<Class Name>
colour colour
An object <Object Name> : <Class Name> “red” “blue”
with data <attribute1 value> radius radius
values <attribute2 value> 1.2 3.5
:
[501043
[CMP167-Unit
Lecture
4-Encapsulation]
3: OOP Part 2]
69
5 UML UML Diagrams (3/3)
[501043
[CMP167-Unit
Lecture
4-Encapsulation]
3: OOP Part 2]
70
6. Exercises
Exercise 1
A class called Circle, which models a circle
6 Exercises
◼
with a radius, is designed as shown in the
following class diagram. Write
the Circle class.
[501043
[CMP167-Unit
Lecture
4-Encapsulation]
3: OOP Part 2]
72
Exercise 2
A class called Rectangle, which models a
6 Exercises
◼
rectangle with a length and a width (in
float), is designed as shown in the following
class diagram. Write the Rectangle class.
[501043
[CMP167-Unit
Lecture
4-Encapsulation]
3: OOP Part 2]
73
Exercise 3
A class called Employee, which models an employee with an ID,
6 Exercises
◼
name and salary, is designed as shown in the following class
diagram. The method raiseSalary(percent) increases the salary by
the given percentage. Write the Employee class.
[501043
[CMP167-Unit
Lecture
4-Encapsulation]
3: OOP Part 2]
74
Summary
◼ OOP concepts discussed :
❑ Encapsulation (tính đóng gói) and information hiding
❑ Constructors, accessors, mutators
❑ Overloading methods
❑ Class and instance members
❑ Using “this” reference and “this” in constructors
❑ Overriding methods
◼ UML
❑ Representing OO components using diagrams
[501043
[CMP167-Unit
Lecture
4-Encapsulation]
3: OOP Part 2]
75
End of file