Tugas P4

advertisement
Tugas P4- OOP
Nama : Sulistiyadi
NIM : 12111070
Soal 1
Screenshot
Source Code Soal1_Lingkaran.java
import java.util.Scanner;
class Lingkaran
{
private double r;
private static final double PI = 3.14;
public Lingkaran(double r)
{
this.r = r;
}
public Lingkaran()
{
this.r = 3.0;
}
public double getRadius()
{
return this.r;
}
public double keliling()
{
return 2 * PI * this.r;
}
public double luas()
{
return r * r * PI;
}
}
public class Soal1_Lingkaran
{
static Scanner inputer = new Scanner(System.in);
public static void main(String[] args)
{
double radius = 10.32;
Lingkaran lingkaran;
System.out.println("Contoh Polimorfisme");
System.out.println("Nama : Sulistiyadi");
System.out.println("NIM
: 12111070\n\n");
lingkaran = new Lingkaran(radius);
System.out.println("Radius
= " + lingkaran.getRadius());
System.out.println("Luas
= " + lingkaran.luas());
System.out.println("Keliling = " + lingkaran.keliling());
}
}
Soal 2
Screenshot
Source Code Soal2_JenisHewan.java
import java.util.Scanner;
abstract class Hewan {
protected String animalSound;
protected int legCount;
public Hewan(int legCount, String animalSound)
{
this.legCount = legCount;
this.animalSound = animalSound;
}
public String describe()
{
String className = getClass().getName();
return "Namaku
= " + className + '\n'
+ "Jumlah kakiku = " + this.legCount + '\n'
+ "Suaraku
= " + this.animalSound + '\n'
+ "----------------------------------------";
}
}
class Kucing extends Hewan
{
public Kucing()
{
super(4, "Miau... Miau...");
}
}
class Burung extends Hewan
{
public Burung()
{
super(2, "Cit... Cit...");
}
}
class Kambing extends Hewan
{
public Kambing()
{
super(4, "Mbek... Mbek...");
}
}
class Sapi extends Hewan
{
public Sapi()
{
super(4, "Moo... Mooo");
}
}
class Ayam extends Hewan
{
public Ayam()
{
super(2, "Kukuruyuk...");
}
}
public class Soal2_JenisHewan
{
public static void main(String[] args) {
Hewan[] peliharaanKu = {
new Kucing(),
new Burung(),
new Kambing(),
new Sapi(),
new Ayam()
};
System.out.println("Program contoh inheritance");
System.out.println("Nama : Sulistiyadi");
System.out.println("NIM : 12111070\n\n");
for (int i = 0; i < peliharaanKu.length; i++) {
System.out.println(peliharaanKu[i].describe());
}
}
}
Download