YULI TRESNAYANTHI

ini adalah blog ku.... tempatku memposting tugas....

Jumat, 08 Januari 2010

Program Class Animal

// 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; itotalWeight += 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

0 Komentar:

Posting Komentar

Berlangganan Posting Komentar [Atom]

<< Beranda