Document - IKB112106 - STMIK EL RAHMA 8. Enkapsulasi

ENKAPSULASI

Enkapsulasi ??
States




Nama
Alamat
Umur

class artis {
String nama;
String alamat;
int umur;
}

Apa
Tipemungkin??
data??


artis artis1 = new artis();
artis1.nama = “Dian Sastro”;
artis1.alamat = “Jln Kalimantan 37 Jember”;
artis1.umur
25.12;
artis1.umur
==
231;

class artis {
String nama;
String alamat;
int umur;
}

Enkapsulasi??
Tdk dpt
diakses scr
langsung


class artis {
private String nama;
private String alamat;
private int umur;

public void setUmur (int umur
this.umur = umur
}
public int getUmur(){
return this.umur;
}
}

Hrs diakses
melalui
method

Enkapsulasi
CLASS

Variabel Instan

Method

ENKAPSULAS
I

Tdk dapat diakses
dari luar kelas

Dapat diakses
dari luar kelas

Enkapsulasi









is the technique of making the fields in a class
private and providing access to the fields via
public methods
can be described as a protective barrier that
prevents the code and data being randomly
accessed by other code defined outside the
class
field is declared private, it cannot be accessed
by anyone outside the class, thereby hiding
the fields within the class. For this reason,
encapsulation is also referred to as data hiding
Using “private” keyword (yg dikenal dng
access modifier)

Why Enkapsulasi??
Benefits of Encapsulation:
 The fields of a class can be controlled
whether it will be read-only or write-only.


ss person{
Tidak dpt diubah (read only)
private String Nama;
private String Pekerjaan;person person1 = new person(“Direktur
person person2 = new person(“OB”);
public person(String Pekerjaan){
this.Pekerjaan = Pekerjaan;
}

public String getPekerjaan(){
return this.Pekerjaan;
}
person1

person2

Why Enkapsulasi??
Benefits of Encapsulation:
 A class can have total control over what

is stored in its fields.

Why Enkapsulasi??
Benefits of Encapsulation:
 The users of a class do not have to know
how the class stores its data. A class can
change the data type of a field, and users
of the class do not need to change any of
their code.

Private vs Public
CLASS
Private Variabel
& Method

Public Variabel &
Method

Access Modifier:
privete

Tdk dapat diakses
dari luar kelas

Access Modifier:
public
Dapat diakses dari
luar kelas

Private vs. Public

Dari kelas lain → main()
s buah{
rivate double hargaBuah;
buah mangga = new buah(();
ublic String warnaBuah;

Tanpa Access Modifier?


Dapat diakses dari seluruh kelas


Dari kelas lain → main()
s buah{
buah mangga = new buah(();
rivate double hargaBuah;
ublic String warnaBuah;
tring bentukBuah;

Tanpa Access Modifier?


Tidak dapat diakses dari luar package

Protected



Hanya dapat diakses oleh subclassnya
(meski dr package lain), TETAPI tdk dpt
diakses oleh client kelas secara langsung.


Package 1

CLASS A

Protected
Variabel &
Method

CLASS B

Package 2

SUBCLASS

CLASS D

CLASS E

Protected




Thx….