Jumat, 08 Januari 2010

TUGAS PBO

// class Animal
public class Animal {
private int weight;

public Animal(int w) { weight=w; }

public void setWeight(int w) { weight = w; }
public int getWeight() { return weight; }
public void talk() {
System.out.println("An animal can't talk");
}
}

// class Cow
public class Cow extends Animal {

public Cow() { super(100); }
public void talk() {
System.out.println("Moo!");
}
}

// class Pig
public class Pig extends Animal {
public Pig() { super(40); }
public void talk() {
System.out.println("Grunt!");
}
}

// class Sheep
public class Sheep extends Animal {
public Sheep() { super(65); }
public void talk() {
System.out.println("Baa!");
}
}

// class Bebek
public class Bebek extends Animal {
public Bebek() { super(35); }
public int jumlahTelur=3;
public void talk() {
System.out.println("Kweek!");

}
}




// class Main
public class FarmExample{
public static void main(String[] args) {
Animal[] farm = {new Cow(), new Pig(), new Sheep(), new Bebek()};
Bebek b = new Bebek();
int totalWeight = 0;

for (int i=0; i
totalWeight += farm[i].getWeight();

System.out.println("The total weight of the " + "animals is " + totalWeight);

System.out.println("The animals say:");
for (int i=0; i
farm[i].talk();

System.out.println("Jumlah Telur Bebek adalah "+b.jumlahTelur);

}
}



Output program :
The total weight of the animals is 240
The animals say:
Moo!
Grunt!
Baa!
Kweek!
Jumlah Telur Bebek adalah 3

Permasalahan Umum Pada Polymorphisme:
Polimorphisme adalah kemampuan dari sebuah ojectuntuk memperbolehkan mengambil beberapa bentuk yang berbeda.Secara harafiah,"poli" berarti banyak sementara "morph" berarti bentuk.Menunjuk pada contoh sebelumnya pada pewarisanDengan polymorphism pekerjaan seorang programmer dapat dimudahkan dengan menuliskan kode yang lebih sedikit. Untuk mengakses class-class turunan tidak dibutuhkan penulisan kode yang berlainan.

Tidak ada komentar: