--

Review Abstract Data Type (OOP)

Tuesday, April 17, 2012 mencoba sebuah karya dunia maya 0 komentar
#include
#include

constream ctk;

struct mahasiswa { char nim[11]; char nama[21];
};

void main(){
ctk.clrscr();

struct mahasiswa a;
do{
ctk << “Masukkan NIM [10 digit]: “; cin >> a.nim;
}while(strlen(a.nim)!=10);

do{
ctk << “Masukkan Nama [max 20 digit]: “; cin >> a.nama;
}while(strlen(a.nama)==0||strlen(a.nama)>20);


ctk << endl << endl;
ctk << “NIM : “ << a.nim << “ Nama : “ << a.nama;

getch();
}

Bentuk umum kelas (OOP)

mencoba sebuah karya dunia maya 0 komentar
class classname {
type instance-variable1;
type instance-variable2;
//…
type instance-variableN;
type methodname1(parameter-list){
//body of method
}
type methodname2(parameter-list){
//body of method
}
//…
type methodnameN(parameter-list){
//body of method
}

}

Kelas sederhana :
class Box {
double width;
double height;
double depth;
}
Cara meng-create objek :
Box mybox = new Box(); create objek Box yang disebut mybox.
Utk mengisi nilai variable width :
mybox.width=100;

Contoh program yang memanggil kelas Box (simpan dalam file BoxDemo.java):

class Box {
double width;
double height;
double depth;
}
class BoxDemo{
public static void main(String args[])
{
Box mybox=new Box();
double vol;
//mengisi nilai variable instant
mybox.width=10;
mybox.height=20;
mybox.depth=15;
//menghitung volume box
vol = mybox.width*mybox.height*mybox.depth;
System.out.println(“Volume = ”+vol);

}
}
Output : Volume = 3000.0

Program berikut mendeklarasikan 2 objek Box.
class Box {
double width;
double height;
double depth;
}
class BoxDemo2{
public static void main(String args[])
{
Box mybox1=new Box();
Box mybox2=new Box();
double vol;
//mengisi nilai variable instant
mybox1.width=10;
mybox1.height=20;
mybox1.depth=15;

mybox2.width=3;
mybox2.height=6;
mybox2.depth=9;

//menghitung volume box
vol = mybox1.width*mybox1.height*mybox1.depth;
System.out.println(“Volume = ”+vol);
vol = mybox2.width*mybox2.height*mybox2.depth;
System.out.println(“Volume = ”+vol);

}
}
Output :
Volume = 3000.0
Volume = 162.0

Assigning object reference variables
Box b1 = new Box();
Box b2 = b1;