Tugas Pertemuan 13 Pemrograman Berbasis Objek (PBO) A 2024
Nama : Amadeo Yesa
NRP : 5025231160
Kelas : A
Tahun : 2024
Pada pertemuan 13, diberikan dua buah studi kasus untuk abstraksi kelas.
1. Implementasi program kecil Abstract Class Makhluk hidup yang diwariskan kepada manusia, hewan, dan tumbuhan.
Class LivingBeing
public abstract class LivingBeing {
protected String name;
public LivingBeing(String name){
this.name = name;
}
public String getName(){
return name;
}
public void breathe(){
System.out.println(name + " is breathing.");
}
public abstract void grow();
}Class Human
public class Human extends LivingBeing {
public Human(String name){
super(name);
}
@Override
public void grow(){
System.out.println(name + " tumbuh menjadi manusia.");
}
public void speak(String sentence){
System.out.println(name + " berkata: " + sentence);
}
}Class Animal
public class Animal extends LivingBeing {
public Animal(String name){
super(name);
}
@Override
public void grow(){
System.out.println(name + " tumbuh menjadi hewan.");
}
public void move(){
System.out.println(name + " sedang bergerak.");
}
}Class Plant
public class Plant extends LivingBeing {
public Plant(String name){
super(name);
}
@Override
public void grow(){
System.out.println(name + " tumbuh menjadi tumbuhan.");
}
public void photosynthesize(){
System.out.println(name + " sedang berfotosintesis.");
}
}Main
public class Main {
public static void main(String[] args) {
System.out.println("--- Manusia ---");
Human human = new Human("Andrew");
human.breathe();
human.grow();
human.speak("Saya bukan monyet.");
System.out.println("\n--- Hewan ---");
Animal animal = new Animal("Kuda");
animal.breathe();
animal.grow();
animal.move();
System.out.println("\n--- Tumbuhan ---");
Plant plant = new Plant("Bayam");
plant.breathe();
plant.grow();
plant.photosynthesize();
}
}Hasil
2. Simulasi Foxes and Rabbits.
Class Animal
import java.util.List;
import java.util.Random;
public abstract class Animal {
protected int age;
protected boolean alive;
protected Field field;
protected Location location;
protected static final Random rand = new Random();
public Animal(boolean randomAge, Field field, Location location){
if(randomAge){
this.age = rand.nextInt(getMaxAge());
}else{
this.age = 0;
}
this.alive = true;
this.field = field;
setLocation(location);
}
public int getAge(){
return age;
}
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){
if(location != null){
field.clear(location);
}
location = newLocation;
field.place(this, newLocation);
}
public boolean canBreed(){
return age >= getBreedingAge();
}
protected void incrementAge(){
age++;
if(age > getMaxAge()){
setDead();
}
}
protected void giveBirth(List<Animal> newAnimals){
if(location == null) return;
List<Location> free = field.allFreeAdjacentLocations(location);
int births = breed();
for(int b = 0; b < births && free.size() > 0; b++){
Location loc = free.remove(0);
Animal young = createOffspring(false, field, loc);
newAnimals.add(young);
}
}
protected int breed(){
int births = 0;
if(canBreed() && rand.nextDouble() <= getBreedingProbability()){
births = rand.nextInt(getMaxLitterSize()) + 1;
}
return births;
}
public abstract void act(List<Animal> newAnimals);
abstract protected int getBreedingAge();
abstract protected int getMaxAge();
abstract protected double getBreedingProbability();
abstract protected int getMaxLitterSize();
abstract protected Animal createOffspring(Field field, Location location);
}Class Rabbit
import java.util.List;
public class Rabbit extends Animal{
private static final int BREEDING_AGE = 5;
private static final int MAX_AGE = 50;
private static final double BREEDING_PROBABILITY = 0.15;
private static final int MAX_LITTER_SIZE = 5;
public Rabbit(boolean randomAge, Field field, Location location){
super(randomAge, field, location);
}
@Override
public void act(List<Animal> newRabbits){
incrementAge();
if(isAlive()){
giveBirth(newRabbits);
Location newLocation = field.freeAdjacentLocation(location);
if(newLocation != null){
setLocation(newLocation);
}else{
setDead();
}
}
}
protected int getBreedingAge(){
return BREEDING_AGE;
}
protected int getMaxAge(){
return MAX_AGE;
}
protected double getBreedingProbability(){
return BREEDING_PROBABILITY;
}
protected int getMaxLitterSize(){
return MAX_LITTER_SIZE;
}
@Override
protected Animal createOffspring(Field field, Location location){
return new Rabbit(false, field, location);
}
}Class Fox
import java.util.List;
import java.util.Iterator;
public class Fox extends Animal{
private static final int RABBIT_ENERGY_VALUE = 10;
private static final int BREEDING_AGE = 10;
private static final int MAX_AGE = 70;
private static final double BREEDING_PROBABILITY = 0.15;
private static final int MAX_LITTER_SIZE = 3;
private static final int INITIAL_ENERGY = 20;
private int energyLevel;
public Fox(boolean randomAge, Field field, Location location){
super(randomAge, field, location);
energyLevel = INITIAL_ENERGY;
}
@Override
public void act(List<Animal> newFoxes){
incrementAge();
incrementHunger();
if(isAlive()){
giveBirth(newFoxes);
Location newLocation = findFood();
if(newLocation == null){
newLocation = field.freeAdjacentLocation(location);
}
if(newLocation != null){
setLocation(newLocation);
}else{
setDead();
}
}
}
private Location findFood(){
List<Location> adjacent = field.adjacentLocations(location);
Iterator<Location> it = adjacent.iterator();
while(it.hasNext()) {
Location where = it.next();
Object animal = field.getObjectAt(where);
if(animal instanceof Rabbit) {
Rabbit rabbit = (Rabbit) animal;
if(rabbit.isAlive()) {
rabbit.setDead();
energyLevel += RABBIT_ENERGY_VALUE;
return where;
}
}
}
return null;
}
private void incrementHunger(){
energyLevel--;
if(energyLevel <= 0){
setDead();
}
}
protected int getBreedingAge(){
return BREEDING_AGE;
}
protected int getMaxAge(){
return MAX_AGE;
}
protected double getBreedingProbability(){
return BREEDING_PROBABILITY;
}
protected int getMaxLitterSize(){
return MAX_LITTER_SIZE;
}
@Override
protected Animal createOffspring(Field field, Location location){
return new Fox(false, field, location);
}
}Class 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;
}
public Object getObjectAt(Location location){
if(location.getRow() >= 0 && location.getRow() < getRow() && location.getCol() >= 0 && location.getCol() < getCol()){
return field[location.getRow()][location.getCol()];
}
return null;
}
public List<Location> allFreeAdjacentLocations(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;
}
public Location freeAdjacentLocation(Location location){
List<Location> free = allFreeAdjacentLocations(location);
if(free.size() > 0){
return free.get(0);
}
return null;
}
public List<Location> adjacentLocations(Location location){
List<Location> locations = new ArrayList<>();
if(location == null){
return locations;
}
int row = location.getRow();
int col = location.getCol();
if(row > 0){
locations.add(new Location(row - 1, col));
}
if(row < getRow() - 1){
locations.add(new Location(row + 1, col));
}
if(col > 0){
locations.add(new Location(row, col - 1));
}
if(col < getCol() - 1){
locations.add(new Location(row, col + 1));
}
return locations;
}
public int getRow(){
return field.length;
}
public int getCol(){
return field[0].length;
}
public void clearAll(){
for(int i=0;i<field.length;i++){
for(int j=0;j<field[i].length;j++){
field[i][j] = null;
}
}
}
}Class Location
public class Location {
private int row;
private int col;
public Location(int row, int col){
this.row = row;
this.col = col;
}
public int getRow(){
return row;
}
public int getCol(){
return col;
}
}Class Simulator
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Iterator;
public class Simulator {
private Field field;
private List<Animal> animals;
private int step;
private SimulatorView view;
private static final int DEFAULT_ROW = 30;
private static final int DEFAULT_COL = 30;
public Simulator(int depth, int width) {
if(width <= 0 || depth <= 0){
System.out.println("The dimensions must be greater than zero.");
System.out.println( "Using default values.");
depth = DEFAULT_ROW;
width = DEFAULT_COL;
}
animals = new ArrayList<Animal>();
field = new Field(depth, width);
view = new SimulatorView(depth, width, field);
view.setSymbol(Rabbit.class, 'R');
view.setSymbol(Fox.class, 'F');
reset();
}
public void simulate(int steps){
for(int step = 0; step < steps; step++){
simulateOneStep();
}
}
public void reset(){
step = 0;
animals.clear();
field.clearAll();
populate();
view.show(step, field);
}
public void simulateOneStep(){
step++;
List<Animal> newAnimals = new ArrayList<Animal>();
for(Iterator<Animal> it = animals.iterator(); it.hasNext();){
Animal animal = it.next();
animal.act(newAnimals);
}
view.show(step, field);
}
private void populate(){
field.clearAll();
double foxProbability = 0.2;
double rabbitProbability = 0.3;
Random rand = new Random();
for(int i=0;i<field.getRow();i++){
for(int j=0;j<field.getCol();j++){
Location location = new Location(i, j);
if(rand.nextDouble() <= foxProbability){
Fox fox = new Fox(false, field, location);
animals.add(fox);
field.place(fox, location);
}
if(rand.nextDouble() <= rabbitProbability){
Rabbit rabbit = new Rabbit(true, field, location);
animals.add(rabbit);
field.place(rabbit, location);
}
}
}
}
}Class SimulatorView
import java.util.HashMap;
import java.util.Map;
public class SimulatorView {
private int row;
private int col;
private Map<Class<?>, Character> symbols;
public SimulatorView(int row, int col, Field field){
this.row = row;
this.col = col;
symbols = new HashMap<Class<?>, Character>();
}
public void setSymbol(Class<?> animal, char symbol){
symbols.put(animal, symbol);
}
public void show(int step, Field field){
System.out.println("Simulation step " + step + ": ");
for(int i=0;i<row;i++){
for(int j=0;j<col;j++){
Object animal = field.getObjectAt(new Location(i, j));
if(animal == null){
System.out.print(". ");
}else{
Character symbol = symbols.get(animal.getClass());
System.out.print((symbol != null ? symbol : '?') + " ");
}
}
System.out.println();
}
System.out.println();
}
}Main
public class Main {
public static void main(String[] args) {
Simulator simulator = new Simulator(10, 10);
simulator.simulate(3);
}
}Hasil
Source Code:


Comments
Post a Comment