A. Inheritance
1. SuperClass.java
public class SuperClass{
public SuperClass() {
System.out.println("Ini Konstruktor milik SuperClass");
}
public void methodSuperClass() {
System.out.println("Ini method milik SuperClass");
}
}
2. SubClass.java
public class SubClass extends SuperClass{
public SubClass() {
super();
}
public void methodSubClass() {
super.methodSuperClass();
}
}
3. DemoInheritance.java
public class DemoInheritance{
public static void main (String[] args) {
SubClass sc = new SubClass();
sc.methodSubClass();
}
}
B. Encapsulation
1. Persegi.java
public class Persegi {
private double panjang; //atribut yang disembunyikan
private double lebar; //atribut yang disembunyikan
private double tinggi; //atribut yang disembunyikan
public Persegi() {
panjang = 0;
lebar = 0;
}
private double luas (double p, double l) {
return p*l;
}
public void setPanjang(double panjang1) {
this.panjang = panjang1;
}
public void setLebar(double lebar1) {
this.lebar = lebar1;
}
public double getPanjang() {
return panjang;
}
public double getLebar() {
return lebar;
}
public double getLuas() {
return luas(panjang, lebar);
}
}
2. MainPersegi.java
public class MainPersegi{
public static void main (String[] args) {
Persegi pg = new Persegi();
pg.setPanjang(10);
pg.setLebar(20);
System.out.println("Panjang : "+pg.getPanjang());
System.out.println("Lebar : "+pg.getLebar());
System.out.println("Luas : "+pg.getLuas());
}
}
Output:
C. Polymorphism
1. Karyawan.java
abstract class Karyawan {
int gaji;
Karyawan() {
gaji = 1000000;
}
int getGaji() {
return gaji;
}
abstract void naikGaji();
}
2. Manager.java
class Manager extends Karyawan {
Manager() {
gaji += 2000000;
}
void naikGaji() { gaji+=3000000; }
}
3. Receptionist.java
class Receptionist extends Karyawan {
Receptionist() {
gaji += 1000000;
}
void naikGaji() { gaji+=1000000; }
}
4. Polymorphisme.java
class Polymorphisme {
public static void main (String[] args) {
Karyawan K[] = new Karyawan[3];
K[0] = new Manager();
K[1] = new Receptionist();
K[2] = new Manager();
for (int i=0;i<3;i++)
System.out.println("Gaji karyawan "+i+" adalah "+K[i].getGaji());
for (int i=0;i<3;i++)
K[i].naikGaji();
for (int i=0;i<3;i++)
System.out.println("Gaji sekarang "+i+" adalah "+K[i].getGaji());
}
}
Output:
Tidak ada komentar:
Posting Komentar