Selasa, 10 Juli 2018

Contoh Program Java; Inheritance

Diagram Class



Buatlah sebuah Project baru di netbean dengan nama Bangun , lalu buat kelas baru dengan nama Persegi dan Kubus , lalu isi kodingnya seperti dibawah ini

Bangun.java

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package bangun;
/**
 *
 * @author awan
 */
public class Bangun {
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        Kubus k1 = new Kubus();
        k1.setSisiKubus(15);
        System.out.println("Luas Permukaan Kubus: "+k1.getLuasPermukaan());
        System.out.println("Keliling Kubus: "+k1.getKelilingKubus());
        System.out.println("Volume Kubus: "+k1.getVolume());
        System.out.println("Keliling setiap Permukaan: "+k1.getKeliling());
    }

}


Persegi.java

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package bangun;
/**
 *
 * @author awan
 */
public class Persegi {
    private int sisi;

    public int getSisi(){
        return sisi;
    }

    public void setSisi(int sisi){
        this.sisi=sisi;
    }

    public Persegi(){
        System.out.println("Class Persegi");
    }
    public int getKeliling(){
       return 4*this.sisi;
    }
    public int getLuas(){
        return sisi*sisi;
    }
}


Kubus.java

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package bangun;
/**
 *
 * @author awan
 */
public class Kubus extends Persegi{
    public void setSisiKubus(int sisi){
        setSisi(sisi);
    }
    public int getKelilingKubus(){
        return 12*getSisi();
    }
    public int getLuasPermukaan(){
        return 6*getLuas();
    }
    public int getVolume(){
        return getSisi()*getSisi()*getSisi();
    }

}
hasil:


Load disqus comments

0 komentar