Contoh Program OOP dengan Inheritance Sederhana dalam Bahasa Java


import java.io.*;
import java.util.Scanner;
class makanan
{
public int porsi;
public double harga;
}
class nasi extends makanan
{
public void setharga()
{
harga = 1000;
}
}
class lauk extends makanan
{
public void setharga()
{
harga = 2000;
}
}
class sayur extends makanan
{
public void setharga(double h) //set harga lewat input user
{
harga = h;
}
public double getharga() //mengambil info harga dr class
{
return(harga);
}
}
public class program //utk menjalankan program utama
{
public static void main(String[] args)
{
double h;
sayur s = new sayur(); //create object utk masing2 class
lauk l = new lauk();
nasi n = new nasi();
Scanner sc = new Scanner(System.in);

System.out.print(“Harga : “);
h = sc.nextDouble();
s.setharga(h);
System.out.println(“Harga sayur :”+s.getharga());
n.harga = 1000; //akses langsung ke atribut
n.porsi = 2;
biaya = n.harga * n.porsi;
System.out.println(“Biaya :”+biaya);

//menu program dan manipulasi object yg lain
//bisa diletakkan di sini
}
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: