--

Bentuk umum kelas (OOP)

Tuesday, April 17, 2012 mencoba sebuah karya dunia maya
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;

0 komentar: Bentuk umum kelas (OOP)

Post a Comment