Abstraction Techniques untuk kelas Pemrograman Obyek Java.docx
1 of 26
More Related Content
Abstraction Techniques untuk kelas Pemrograman Obyek Java.docx
1. Abstraction Techniques
1. Overview
ï‚· Abstraction adalah konsep inti dalam pemrograman berorientasi objek yang
bertujuan menyembunyikan detail implementasi dan hanya menampilkan
fungsi penting kepada pengguna.
ï‚· Pada chapter ini, fokus akan diberikan pada teknik-teknik abstraksi lebih lanjut
yang membantu membuat kode lebih modular, dapat digunakan kembali, dan
lebih mudah dipahami.
2. Key Concepts in Further Abstraction
Interfaces
o Sebuah interface adalah sebuah tipe abstrak yang mendefinisikan
sekumpulan metode tanpa implementasi.
o Digunakan untuk mendukung polymorphism dan memastikan bahwa
kelas yang berbeda dapat berinteraksi meskipun mereka memiliki
implementasi berbeda.
o Contoh:
public interface Drivable {
void startEngine();
void stopEngine();
}
Abstract Classes
ï‚· Kelas abstrak adalah kelas yang tidak bisa diinstansiasi langsung dan sering kali
digunakan sebagai base class.
ï‚· Kelas ini dapat memiliki metode abstrak (tanpa implementasi) dan metode
konkret (dengan implementasi).
ï‚· Contoh
public abstract class Vehicle {
private String model;
public Vehicle(String model) {
this.model = model;
}
public String getModel() {
1
2. return model;
}
public abstract void move();
}
Generalization and Specialization
ï‚· Teknik untuk mengidentifikasi atribut dan perilaku umum (generalization) serta
memisahkan fitur unik ke subclass (specialization).
ï‚· Meningkatkan keterbacaan kode dan memudahkan perawatan.
Composition Over Inheritance
ï‚· Menggunakan objek lain di dalam kelas (komposisi) untuk memperluas
fungsionalitas dibandingkan bergantung sepenuhnya pada pewarisan.
ï‚· Contoh
public class Engine {
public void start() {
System.out.println("Engine starts.");
}
}
public class Car {
private Engine engine = new Engine();
public void startCar() {
engine.start();
}
}
Design by Contract
o Memastikan interaksi antara kelas dan objek mengikuti kontrak yang
jelas, biasanya melalui antarmuka.
o Membantu menjaga integritas sistem.
2
3. 3. Examples and Use Cases
ï‚· Polymorphism Example:
public class Bicycle implements Drivable {
@Override
public void startEngine() {
System.out.println("Bicycle has no engine to start.");
}
@Override
public void stopEngine() {
System.out.println("Bicycle has no engine to stop.");
}
}
Abstract Class Example:
public class Car extends Vehicle {
public Car(String model) {
super(model);
}
@Override
public void move() {
System.out.println("Car is moving.");
}
}
Dengan Abstract Class
ï‚· Mempermudah pengembangan dan pemeliharaan kode.
ï‚· Memperluas fleksibilitas melalui penggunaan polymorphism.
ï‚· Mendorong penggunaan kembali kode.
3
4. Contoh 1
Desain Kelas
1. Abstract Class: LivingBeing
ï‚· Semua makhluk hidup memiliki beberapa properti dan metode umum seperti
breathe dan grow.
2. Abstract Class: Human, Animal, Plant
ï‚· Setiap kelompok makhluk hidup memiliki sifat khusus. Misalnya:
o Human: Berbicara.
o Animal: Bergerak dengan cara tertentu.
o Plant: Melakukan fotosintesis.
3. Subclass
ï‚· Human: Programmer dan Doctor.
ï‚· Animal: Dog dan Bird.
ï‚· Plant: FloweringPlant dan NonFloweringPlant.
Implementasi Kode
Abstract Class: LivingBeing
public abstract class LivingBeing {
private String name;
public LivingBeing(String name) {
this.name = name;
}
public String getName() {
return name;
}
4
5. // Common method
public void breathe() {
System.out.println(name + " is breathing.");
}
// Abstract method
public abstract void grow();
}
Abstract Class: Human
public abstract class Human extends LivingBeing {
public Human(String name) {
super(name);
}
public abstract void speak();
}
Abstract Class: Animal
public abstract class Animal extends LivingBeing {
public Animal(String name) {
super(name);
}
public abstract void move();
}
Abstract Class: Plant
public abstract class Plant extends LivingBeing {
public Plant(String name) {
super(name);
}
5
6. public abstract void photosynthesize();
}
Implementasi Subclass
Human Subclass
public class Programmer extends Human {
public Programmer(String name) {
super(name);
}
@Override
public void grow() {
System.out.println(getName() + " is learning new programming languages to grow
intellectually.");
}
@Override
public void speak() {
System.out.println(getName() + " is explaining coding concepts.");
}
}
public class Doctor extends Human {
public Doctor(String name) {
super(name);
}
@Override
6
7. public void grow() {
System.out.println(getName() + " is gaining experience through practice.");
}
@Override
public void speak() {
System.out.println(getName() + " is consulting with patients.");
}
}
Animal Subclass
public class Dog extends Animal {
public Dog(String name) {
super(name);
}
@Override
public void grow() {
System.out.println(getName() + " is growing by eating and exercising.");
}
@Override
public void move() {
System.out.println(getName() + " is running on four legs.");
}
}
public class Bird extends Animal {
public Bird(String name) {
super(name);
7
8. }
@Override
public void grow() {
System.out.println(getName() + " is growing by eating seeds.");
}
@Override
public void move() {
System.out.println(getName() + " is flying in the sky.");
}
}
Plant Subclass
public class FloweringPlant extends Plant {
public FloweringPlant(String name) {
super(name);
}
@Override
public void grow() {
System.out.println(getName() + " is growing by producing flowers.");
}
@Override
public void photosynthesize() {
System.out.println(getName() + " is producing food through photosynthesis.");
}
}
8
9. public class NonFloweringPlant extends Plant {
public NonFloweringPlant(String name) {
super(name);
}
@Override
public void grow() {
System.out.println(getName() + " is growing without producing flowers.");
}
@Override
public void photosynthesize() {
System.out.println(getName() + " is photosynthesizing without flowers.");
}
}
Main Program
public class Main {
public static void main(String[] args) {
// Humans
Human programmer = new Programmer("Alice");
Human doctor = new Doctor("Bob");
programmer.breathe();
programmer.grow();
programmer.speak();
doctor.breathe();
doctor.grow();
9
10. doctor.speak();
// Animals
Animal dog = new Dog("Buddy");
Animal bird = new Bird("Tweety");
dog.breathe();
dog.grow();
dog.move();
bird.breathe();
bird.grow();
bird.move();
// Plants
Plant rose = new FloweringPlant("Rose");
Plant fern = new NonFloweringPlant("Fern");
rose.breathe();
rose.grow();
rose.photosynthesize();
fern.breathe();
fern.grow();
fern.photosynthesize();
}
}
10
12. Contoh 2
Studi Kasus: The Foxes and Rabbits Simulation
Studi kasus ini diambil dari Object First Chapter 10: Further Abstraction Techniques.
Simulasi ini dirancang untuk menggambarkan interaksi antara dua jenis hewan—rubah
(foxes) dan kelinci (rabbits)—dalam lingkungan tertentu. Tujuan utamanya adalah
mempelajari bagaimana abstraksi diterapkan untuk membuat desain kode lebih
modular, fleksibel, dan mudah dipelihara.
Deskripsi Sistem
1. Komponen Utama:
o Field: Representasi ruang tempat rubah dan kelinci tinggal.
o Simulator: Bertugas menjalankan simulasi dan mengontrol langkah-
langkahnya.
o Animal: Abstraksi umum untuk semua hewan.
o Rabbit dan Fox: Subkelas spesifik yang memperluas Animal.
2. Perilaku Hewan:
o Hewan memiliki metode abstrak seperti act() yang menentukan tindakan
mereka di setiap langkah simulasi.
o Kelinci hanya bergerak, sedangkan rubah dapat memangsa kelinci.
3. Lingkungan:
o Simulasi berlangsung di sebuah grid di mana setiap sel bisa kosong atau
ditempati oleh hewan.
4. Konsep Utama:
o Inheritance: Kelas Animal digunakan sebagai superclass untuk Rabbit dan
Fox.
o Abstraction: Beberapa metode didefinisikan abstrak untuk dipaksa
diimplementasikan oleh subclass.
Implementasi Kode
1. Kelas Abstract: Animal
public abstract class Animal {
private int age;
12
13. private boolean alive;
private Field field;
private Location location;
public Animal(Field field, Location location) {
this.age = 0;
this.alive = true;
this.field = field;
setLocation(location);
}
public boolean isAlive() {
return alive;
}
public void setDead() {
alive = false;
if (location != null) {
field.clear(location);
location = null;
field = null;
}
}
public Location getLocation() {
return location;
}
public void setLocation(Location newLocation) {
13
14. if (location != null) {
field.clear(location);
}
location = newLocation;
field.place(this, newLocation);
}
public abstract void act(List<Animal> newAnimals);
}
2. Subclass: Rabbit
import java.util.List;
public class Rabbit extends Animal {
public Rabbit(Field field, Location location) {
super(field, location);
}
@Override
public void act(List<Animal> newAnimals) {
if (isAlive()) {
Location newLocation = getField().freeAdjacentLocation(getLocation());
if (newLocation != null) {
setLocation(newLocation);
} else {
setDead();
}
}
}
14
15. }
3. Subclass: Fox
import java.util.List;
public class Fox extends Animal {
public Fox(Field field, Location location) {
super(field, location);
}
@Override
public void act(List<Animal> newAnimals) {
if (isAlive()) {
Location newLocation = findFood();
if (newLocation == null) {
newLocation = getField().freeAdjacentLocation(getLocation());
}
if (newLocation != null) {
setLocation(newLocation);
} else {
setDead();
}
}
}
private Location findFood() {
List<Location> adjacent = getField().adjacentLocations(getLocation());
for (Location loc : adjacent) {
Object animal = getField().getObjectAt(loc);
15
16. if (animal instanceof Rabbit) {
Rabbit rabbit = (Rabbit) animal;
rabbit.setDead();
return loc;
}
}
return null;
}
}
4. Kelas Pendukung: Field dan Location
Field
import java.util.List;
import java.util.ArrayList;
public class Field {
private Object[][] field;
public Field(int depth, int width) {
field = new Object[depth][width];
}
public void clear(Location location) {
field[location.getRow()][location.getCol()] = null;
}
public void place(Object object, Location location) {
field[location.getRow()][location.getCol()] = object;
}
16
17. public Object getObjectAt(Location location) {
return field[location.getRow()][location.getCol()];
}
public Location freeAdjacentLocation(Location location) {
List<Location> free = new ArrayList<>();
List<Location> adjacent = adjacentLocations(location);
for (Location loc : adjacent) {
if (getObjectAt(loc) == null) {
free.add(loc);
}
}
return free.isEmpty() ? null : free.get(0);
}
public List<Location> adjacentLocations(Location location) {
List<Location> locations = new ArrayList<>();
// Add logic to calculate adjacent locations
return locations;
}
}
Location
public class Location {
private int row;
private int col;
public Location(int row, int col) {
this.row = row;
17
18. this.col = col;
}
public int getRow() {
return row;
}
public int getCol() {
return col;
}
}
5. Simulator
import java.util.ArrayList;
import java.util.List;
public class Simulator {
private Field field;
private List<Animal> animals;
public Simulator(int depth, int width) {
field = new Field(depth, width);
animals = new ArrayList<>();
populate();
}
public void simulate(int steps) {
for (int step = 0; step < steps; step++) {
List<Animal> newAnimals = new ArrayList<>();
18
19. for (Animal animal : animals) {
animal.act(newAnimals);
}
animals.addAll(newAnimals);
}
}
private void populate() {
// Add logic to populate the field with foxes and rabbits
}
}
19
20. Latihan
Studi Kasus: Sistem Transportasi Umum
Latar Belakang
Sebuah perusahaan transportasi umum ingin mengembangkan sistem untuk
mengelola berbagai jenis kendaraan seperti bus, kereta api, dan kapal. Semua
kendaraan harus memiliki fitur dasar seperti memulai perjalanan (start) dan berhenti
(stop). Beberapa kendaraan dapat melakukan fungsi tambahan, seperti terbang atau
berlayar.
Tujuan
Mengimplementasikan sistem menggunakan konsep abstract class dan interface untuk
menangani generalisasi dan fitur khusus dari masing-masing kendaraan.
Desain Sistem
1. Abstract Class: Vehicle
o Vehicle mendefinisikan atribut dan metode umum yang dimiliki semua
kendaraan.
o Memiliki metode abstrak start dan stop.
2. Interface: Flyable dan Sailable
o Flyable untuk kendaraan yang bisa terbang (misalnya pesawat).
o Sailable untuk kendaraan yang bisa berlayar (misalnya kapal).
3. Subclass: Bus, Train, Plane, Ship
o Masing-masing kelas mengimplementasikan metode dari kelas abstrak
dan antarmuka sesuai kebutuhan.
Implementasi Kode
Abstract Class: Vehicle
public abstract class Vehicle {
private String name;
public Vehicle(String name) {
this.name = name;
20
21. }
public String getName() {
return name;
}
// Abstract methods
public abstract void start();
public abstract void stop();
}
Interface: Flyable dan Sailable
public interface Flyable {
void takeOff();
void land();
}
public interface Sailable {
void anchor();
void sail();
}
Subclass: Bus
public class Bus extends Vehicle {
public Bus(String name) {
super(name);
}
@Override
public void start() {
21
22. System.out.println(getName() + " is starting its journey on the road.");
}
@Override
public void stop() {
System.out.println(getName() + " has stopped at the bus station.");
}
}
Subclass: Train
public class Train extends Vehicle {
public Train(String name) {
super(name);
}
@Override
public void start() {
System.out.println(getName() + " is departing from the station.");
}
@Override
public void stop() {
System.out.println(getName() + " has arrived at the station.");
}
}
Subclass: Plane
public class Plane extends Vehicle implements Flyable {
22
23. public Plane(String name) {
super(name);
}
@Override
public void start() {
System.out.println(getName() + " is starting its engines.");
}
@Override
public void stop() {
System.out.println(getName() + " has stopped its engines.");
}
@Override
public void takeOff() {
System.out.println(getName() + " is taking off.");
}
@Override
public void land() {
System.out.println(getName() + " is landing.");
}
}
Subclass: Ship
public class Ship extends Vehicle implements Sailable {
public Ship(String name) {
super(name);
23
24. }
@Override
public void start() {
System.out.println(getName() + " is starting its voyage.");
}
@Override
public void stop() {
System.out.println(getName() + " has docked at the harbor.");
}
@Override
public void anchor() {
System.out.println(getName() + " is anchoring.");
}
@Override
public void sail() {
System.out.println(getName() + " is sailing on the sea.");
}
}
Main Program
public class Main {
public static void main(String[] args) {
Vehicle bus = new Bus("City Bus");
Vehicle train = new Train("Express Train");
24