a. 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");
}
}
b. class Cow
public class Cow extends Animal {
public Cow() { super(100); }
public void talk() {
System.out.println("Moo!");
}
}
c. class Pig
public class Pig extends Animal{
public Pig() { super(40); }
}
d. class Sheep
public class Sheep extends Animal{
public Sheep() { super(65); }
}
e. Main Program/ Class FarmExample2
public class FarmExample2 {
public static void main(String[] args) {
Animal[] farm = {new Cow(), new Pig(),
new Sheep()};
int totalWeight = 0;
for (int i=0; i
System.out.println("The total weight of the animals is " + totalWeight);
}
}
Keluaran program:
The total weight of the animals is 205
2. Class Bebek
a. 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");
}
}
b. class Bebek
public class Bebek extends Animal{
int numberOfEggs;
public Bebek() {
super(4); // panggil constructor induk
numberOfEggs = 15;}
public void talk() {
System.out.println(" Bebek Berbunyi Kwek...kwek!");}
public int getNumberOfEggs() {
return numberOfEggs;}
public void setNumberOfEggs(int n) {
numberOfEggs = n;}
}
c. Main Program
public class FarmExample3 {
public static void main(String[] args) {
Animal[] farm = {new Bebek()};
for (int i=0; i
System.out.println(" Memiliki " +((Bebek)farm[i]).getNumberOfEggs()+ " Telur");
}
}
}
Keluaran program :
Bebek Berbunyi Kwek…kwek!
Memiliki 15 Telur
3. Java tidak mendukung Multiple Inheritance secara murni.
Mengapa?
Karena fitur yang ada pada bahasa Java saat ini belum mendukung adanya multiple inheritance secara murni, tetapi multiple inheritance dalam java bisa didapat dengan memamfaatkan fitur interface. Didalam java hanya mendukung adanya Single Inheritance secara murni. Multiple Inherintance secara murni bisa di dapat pada bahasa sejenis C, dan C++.
Tidak ada komentar:
Posting Komentar