0% found this document useful (0 votes)
4 views70 pages

6 Encapsulation

The document covers the concept of encapsulation in object-oriented programming, focusing on classes, objects, attributes, methods, and access modifiers. It emphasizes the importance of data protection through encapsulation, using getters and setters to manage access to private fields. Additionally, it discusses class design, constructors, method overloading, and the use of packages in Java programming.

Uploaded by

khoilaomelette
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views70 pages

6 Encapsulation

The document covers the concept of encapsulation in object-oriented programming, focusing on classes, objects, attributes, methods, and access modifiers. It emphasizes the importance of data protection through encapsulation, using getters and setters to manage access to private fields. Additionally, it discusses class design, constructors, method overloading, and the use of packages in Java programming.

Uploaded by

khoilaomelette
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 70

Encapsulation

Objectives
• Class and Object
• How to identify classes
• Hints for class design
• How to declare/use a class
• Current object
• Member functions
• Concept Package
• Access modifiers (a way to hide some members in a
class)
• Case study
The concept of an object
• Real-world object representation
• Each object is characterized by its own
properties and behaviors
Traits and behavior

• Characteristics
• Manufacturer
• Model
• Five
• Color
• Behavior (What can a car do?)
• Start up
• Stop
• Brake
• Turn on the wipers
Class

Car Animal
Class definition
• A class is a template used to describe
objects of the same type.
• The class consists of properties (data
fields) and methods (member functions).
Attributes and methods

• Attributes (fields)

Danh từ
• Manufacturer
• Model
• Five
• Color
• Method (method)
Động từ

• Start()
• Stop()
• Brake()
• Turn on wiper()
Attributes and methods
Ô tô

Thuộc tính
• Năm
• Nhà sản xuất
Ô tô của Dũng • Model Ô tô của Mai
• Màu
Phương thức
Thuộc tính Thuộc tính
• Khởi động
• Năm = 2010 • Năm = 2012
• Dừng
• Nhà SX=Honda • Nhà SX=BMW
• Phanh
• Model = Accord • Model = CS30
• Màu = Xanh • Màu = Bạc
Phương thức Phương thức
• Khởi động • Khởi động
• Dừng • Dừng
• Phanh • Phanh
class
Khai báo các trường
class <<ClassName>>
{
<<type>> <<field1>>;
Khai báo các phương thức

<<type>> <<fieldN>>;

<<type>> <<method1>>([parameters]) {
// body of method
}

<<type>> <<methodN>>([parameters]) {
// body of method
}
}
Ex
Trường

Phương thức

Lớp Employee có 2 thuộc tính là fullname và salary và 2 phương thức là input() và output()
Create object
• The following code uses the Employee class to
create an employee then calls the methods of the
class.

• Attention:
• The new operator is used to create objects
• The emp variable contains a reference to the object
• Use dot (.) to access class members (fields and
methods).
DEMO
Create a student description class
including full name, grade, and
methods of input, output, and
academic rating
Định nghĩa phương thức
Method definition
• A method is a module of code that does a
specific job
• In Employee class, there are 2 methods input() and
output().
• The method can have one or more parameters
• The method can have a return type or void
(returns nothing).
• Syntax
<<return type>> <<method name>> ([parameter list])
{
// method body
}
thức

Kiểu trả về là void nên thân phương thức


không chứa lệnh return giá trị

Kiểu trả về là double nên thân phương


thức phải chứa lệnh return số thực

overloading
In a class there can be many methods with
the same name but different parameters
(type, number and order).

public class MyClass{


void method(){…}
void method(int x){…}
void method(float x){…}
void method(int x, double y){…}
}

• In the MyClass class, there are 4 methods


with the same name, but different
parameters
EX
• Consider the following overload case

class MayTinh{
int tong(int a, int b){return a + b;}
int tong(int a, int b, int c){return a + b + c;}
}

• With the above class you can use to sum


2 or 3 integers.
MayTinh mt = new MayTinh();
int t1 = mt.tong(5, 7);
int t2 = mt.tong(5, 7, 9);
• constructor
constructor (constructor)
• A constructor is a special method used to
create an object.
• Features of the constructor
• Same name as class name
• No return value
• For example Lớp
public class ChuNhat{
double dai, rong;
public ChuNhat(double dai, double rong){
this.dai = dai;
this.rong = rong; Đối tượng
}
ChuNhat cn1 = new ChuNhat(20, 15);
}
ChuNhat cn2 = new ChuNhat(50, 25);
constructor
• In a class, many constructors with different
parameters can be defined, each of which
provides a way to create an object.
• If no constructor is declared, Java
automatically provides a default
public class ChuNhat{
constructor
double dai, rong;(no parameters).
public ChuNhat(double dai, double rong){
this.dai = dai;
this.rong = rong;
}
public ChuNhat(double canh){
this.dai = canh;
this.rong = canh; ChuNhat cn = new ChuNhat(20, 15);
} ChuNhat vu= new ChuNhat(30);
}
this
• this is used to represent the current object.
• this is used in the class to refer to the
members of the class (fields and methods).
• Use this.field to distinguish fields from local
variables or method parameters

public class MyClass{


int field;
void method(int field){
this.field = field;
}
} Trường Tham số
SinhVien

+ hoTen: String
+ diemTB: double
+ xepLoai(): String
+ xuat(): void

DEMO
+ nhap(): void
+ SinhVien()
+ SinhVien(hoTen, diemTB)

Xây dựng lớp mô tả sinh viên như mô hình


trên. Trong đó nhap() cho phép nhập họ tên
và điểm từ bàn phím; xuat() cho phép xuất
họ tên, điểm và học lực ra màn hình;
xepLoai() dựa vào điểm để xếp loại học lực
Sử dụng 2 hàm tạo để tạo 2 đối tượng sinh
viên
Lab 4 buổi 1

• Lab 4 – bài 1
• Lab 4 – bài 2
Package
• Packages are used to divide classes and
interfaces into different packages.
• This is similar to managing files on the drive in that
class (file) and package (folder)
• The following example creates class MyClass in
package com.poly
package com.poly;
public class MyClass{…}

• In Java, there are many packages classified by


function
• java.util: contains utility classes
• java.io: contains data input/output classes
• java.lang: contains commonly used classes…
Import package
• The import statement is used to specify
the class defined in a package
• Classes in the java.lang package and
classes defined in the same package as
the user class will be imported implicitly
package com.polyhcm;
import com.poly.MyClass;
import java.util.Scanner;
public class HelloWorld{
public static void main(String[] args){
MyClass obj = new MyClass();
Scanner scanner = new Scanner(System.in);
}
}
Access specification

• The access specification is used to define the ability to


allow access to class members. In java there are 4
different specifications:
• private: is only allowed to be used internally within the class
• public: fully public
• {default}:
• Is public to classes accessing the same package
• Is private to access classes other than the package.
• protected: similar to {default} but allows inheritance even
though the subclass and parent are in different packages.
• The degree of concealment increases in the direction of
the arrow
public protected {default} private
Access specification
package p1;
public class A{
public int a;
protected int b;
int c;
private int d;

extends
}
use

use
package p1; package p2; package p3;
public class B{ public class C{ public class D extends A{
A x = new A(); A x = new A(); void method(){
void method(){ void method(){ a = 1;
x.a = 1; x.a = 1; b = 1;
x.b = 1; x.b = 1; c = 1;
x.c = 1; x.c = 1; d = 1;
x.d = 1; x.d = 1; }
} } }
} }
Encapsulation

• Encapsulation is object-oriented masking.


• Should hide data fields
• Using methods to retrieve data fields
• The purpose of concealment
• Data Protection
• Enhanced scalability
Non-Encapsulation
• Suppose you define SinhVien class and
public hoTen and score as follows
public class MyClass{
public static void main(String[] args){
public class SinhVien{
SinhVien sv = new SinhVien();
public String hoTen;
sv.hoTen = “Nguyễn Văn Tèo”;
public double diem;
sv.diem = 20.5;
}
}
}

• When using the user can assign data to


the fields arbitrarily
• What if the valid score is only from 0 to 10
Encapsulation
• To hide information, use private for data fields.
private double diem;
• Add getter and setter methods to read and
write hidden fieldspublic void setDiem(double
diem){
this.diem = diem;
}
public String getDiem(){
return this.diem;
}
Encapsulation
public class SinhVien{
private String hoTen; Just add

private double diem;
public void setHoTen(String hoTen){ code to the
this.hoTen = hoTen; setDiem()
}
public String getHoTen(){ method to
return this.hoTen;
}
take action
public void setDiem(double diem){ when the
if(diem < 0 || > 10){
System.out.println(“Điểm không họp lệ”);data is invalid
}
else{ public class MyClass{
this.diem = diem; public static void main(String[] args){
} SinhVien sv = new SinhVien();
} sv.setHoTen(“Nguyễn Văn Tèo”);
public String getDiem(){ sv.setDiem(20);
return this.diem; }
} }
}
Quản lý sinh viên, sử dụng tính chất Encapsulation để
bảo vệ và quản lý thông tin sinh viên.
Yêu cầu bài toán
•Lớp Student
•Chứa thông tin sinh viên: ID, tên, tuổi, điểm
trung bình (GPA).
•Các thuộc tính phải được đóng gói (private).
•Chỉ có thể truy cập thông qua getter và setter
(public).
•Kiểm tra dữ liệu nhập vào (tuổi > 0, GPA từ 0.0
đến 4.0).
•Lớp StudentManager
•Quản lý danh sách sinh viên bằng mảng động
(ArrayList<Student>).
•Cung cấp chức năng thêm, hiển thị danh sách
sinh viên.
•Lớp Main
•Tạo đối tượng StudentManager.
•Thêm sinh viên và hiển thị danh sách.
•Cập nhật thông tin sinh viên bằng setter.
Encapsulation

Aggregation of data and behavior.


– Class = Data (fields/properties) + Methods
– Data of a class should be hidden from the outside.
– All behaviors should be accessed only via methods.
– A method should have a boundary condition: Parameters
must be checked (use if statement) in order to assure that
data of an object are always valid.
– Constructor: A special method it’s code will execute when
an object of this class is initialized.
– Getters/Setters: implementing getter and setter is one of
the ways to enforce encapsulation in the program’s code.
How to Identity a Class
• Main noun: Class
• Nouns as modifiers of main noun: Fields
• Verbs related to main noun: Methods
For example, details of a Main noun: Student
Auxiliary nouns:code , name,
student include code, name, bYear, address;
year of birth, address. verbs: input() , output()
Write a Java program that will
allow input a student, output
his/her.
Hints for class design

A UML class diagram is used to represent


the Student class
Student class

Code: String
name: String fields
bYear: int
address: String

Input(): void methods


output():void

Note: We can add more some functions


Hints for class design
Head
• Identifying classes: Coupling Eye1 High coupling
• Is an object’s reliance on Eye2 ( Bad design)

knowledge of the internals of


another entity’s implementation.
• When object A is tightly coupled
to object B, a programmer who
wants to use or modify A is Head Eye
required to have an leftEye
inappropriately extensive rightEye
Eye
expertise in how to use B.
Low coupling
( Good design)
Hints for class design
• Implementing methods: Cohesion is the degree to
which a class or method resists being broken down
into smaller pieces.
class A
M1()
{
class A Operation 1
M() }
{ M2()
Operation 1
{
Operation 2 Operation 2
} }
M()
Low cohesion(bad design) { M1(); M2();
}

High cohesion(good design)


Declaring/Using a Java Class

[public] class ClassName [extends FatherClass] {


[modifier] Type field1 [= value];
[modifier] Type field2 [= value]; Modifiers will be
// constructor introduced later.
[modifier] ClassName (Type var1,…) {
<code>
} How many
constructors should
[modifier] Type methodName (Type var1,…) {
be implemented? 
<code> Number of needed
} ways to initialize an
……. object.
}
What should we will write in constructor’s body?  They usually
are codes for initializing values to descriptive variables
Constructors

• Constructors that are invoked to create


objects from the class blueprint.
• Constructor declarations look like method
declarations—except that they use the
name of the class and have no return type.
• The compiler automatically provides a no-
argument, default constructor for any class
without constructors.
Constructors

//default constructor
public Student(){
code=“SE123”;
name=“Hieu”;
bYear= 2000;
address=“1 Ba Trieu , HN”.
}
//constructor with parameters
public Student(String code, String name, int bYear, String address){
this.code=code;
this.name=name;
this.bYear= year;
this.address=address.
}
The current object: this

• The keyword this returns the address of the current


object.
• This holds the address of the region of memory that
contains all of the data stored in the instance variables of
current object.
• Scope of this: this is created and used just when the
member method is called. After the member method
terminates this will be discarded
Member functions
• Member functions are the functions, which
have their declaration inside the class
definition and work on the data members
of the class.
• Typical method declaration:
[modifier] ReturnType methodName (params)
{
<code>
}
• Signature: data help identifying something
• Method Signature: name + order of parameter types
Member functions: Getter/Setter
• A getter is a method that gets the value of
a property.
• A setter is a method that sets the value of
a property.
• Uses:
for completeness of encapsulation
to maintain a consistent interface in case
internal details change
Member functions: Getter/Setter

• For example:
public String getName(){
return name;
}
public void setName(String name){
if(! name.isEmpty())
this.name=name;
}
Member functions:
other methods
• For example:
public void input(){
//code here
}
public void output(){
//code here
}
Passing Arguments a Constructor/Method

• Java uses the mechanism passing by


value. Arguments can be:
– Primitive Data Type Arguments
– Reference Data Type Arguments (objects)
Creating Objects

• Class provides the blueprint for objects; you create an


object from a class.
Student stu = new
Student(“SE123”,”Minh”,2000,”1 Ba Trieu”);
• Statement has three parts:
– Declaration: are all variable declarations that associate a
variable name with an object type.
– Instantiation: The new keyword is a Java operator that
creates the object (memory is allocated).
– Initialization: The new operator is followed by a call to a
constructor, which initializes the new object (values are
assigned to fields).
Type of Constructors
Create/Use an object of a class
• Default constructor: Constructor with no parameter.
• Parametric constructor: Constructor with at least one
parameter.

• Create an object
ClassName obj1=new ClassName();
ClassName obj2=new ClassName(params);
• Accessing a field of the object
object.field
• Calling a method of an object
object.method(params)
Demo: If we do not implement any
constructor, compiler will insert to the class a
system default constructor

In this demonstration (package


point1):
- The class IntPoint1 represents a
point in an integral two
dimensional coordinate.
- The class IntPoint1_Use having
the main method in which the
class IntPoint1 is used.
Demo: If we do not implement any
constructor, compiler will insert to the class a
default constructor
System constructor will clear all
bits in allocated memory Order for
initializing an
object

(2) Setup
values

y 0
100 x 0

(1) Memory
allocation

An object variable is a reference p 100


Demo: If we implement a constructor,
compiler does not insert default constructor

This demonstration will depict:


- The way to insert some
methods automatically in
NetBeans
- If user-defined constructors
are implemented, compiler
does not insert the system
default constructor
Demo: If we implement a constructor,
compiler does not insert default constructor
Insert constructor

Parameter names are the same as those


in declared data filed. So, the keyword
this will help distinguish field name and
parameter name.
this.x means that x of this object
Demo: If we implement a constructor,
compiler does not insert default constructor
Accessing each data field is usually supported by :
A getter for reading value of this field
Insert getter/setter A setter for modifying this field
Demo: If we implement a constructor,
compiler does not insert system constructor
Explain the result of the following program
What Is a Package?
• A package is a namespace that organizes
a set of related classes and interfaces.
• The Java platform provides an enormous
class library (a set of packages) suitable
for use in your own applications called
API.
• For example, a String object contains state and
behavior for character strings.
User-Defined Package
• Add a Java
class

If package is used, it must be


the first line in Java code
User-Defined Package
Access modifiers
• Modifier (linguistics)is a word which can bring out the
meaning of other word (adjective noun, adverb  verb)
• Modifiers (OOP) are keywords that give the compiler
information about the nature of code (methods), data,
classes.
• Java supports some modifiers in which some of them are
common and they are called as access modifiers
(public, protected, private).
• Access modifiers will impose level of accessing on
• class (where it can be used?)
• methods (whether they can be called or not)
• fields (whether they may be read/written or not)
Outside of a Class

Inside of the class


Inside of the InPoint2_Use and it is
class InPoint2 outside of the class
IntPoint2

Outside of the class A is another class


where the class A is accessed (used)
Access Modifiers
Order:
public > protected > default > private
Access level
Applied to
Free-accessing public

interface
package/ subclass

protected
class
outside cannot access
private
members of
interface/class
package
no specifier
(default)
Interface is a group of prototyped
methods and they will be
Note: If you don't use any modifier, it is implemented in a class afterward.
treated as default by default. It will be introduced later.
Access Modifiers

super: Keyword for calling a


member declared in the father
class.
If contructor of sub-class calls
a constructor of it’s father
using super, it must be the
first statement in the sub-class
constructor.
Demo: Methods with
Arbitrary Number of Arguments
A group is treated as an array
group.length number of elements
group[i]: The element at the position i
Case study
• Problem:
A sports car can be one of a variety of colours,
with an engine power between 100 HP and 200
HP. It can be a convertible or a regular model.
The car has a button that starts the engine and a
parking brake. When the parking brake is
released and you press the accelerator, it drives
in the direction determined by the transmission
setting.
Report…
Class Design
From the problem description, concepts in the problem domain
are expressed by following classes:
Report…
• A UML class diagram is used to represent
the Car class

Car

- Colour: String
- EnginePower: int
- Convertible: boolean
- parkingBrake: boolean

+Car()
+Car(String, int, boolean, boolean )
+pressStartButton():void
+pressAcceleratorButton(): void
+ getColour(): String
+ setColour(String): void

Implement
Implement
Implement
Summary
• The anatomy of a class, and how to declare
fields, methods, and constructors.
• Hints for class design:
• Main noun  Class
• Descriptive nouns  Fields
• Methods: Constructors, Getters, Setters, Normal methods
• Creating and using objects.
• To instantiate an object: Using appropriate
constructors
• Use the dot operator to access the object's
instance variables and methods.

You might also like