Rabu, 21 Oktober 2009

Tugas JAVA

1.Superclass dan Subclass
//================================================
// Superclass Laptop
//================================================
class Laptop
{
private String tipe; //variabel superkelas

public Motor(String aTipe) //constructor superkelas
{
tipe=new String(aTipe);
}

public String jenisLaptop()
{

return"Ini adalah" + tipe;

}

}

//===============================================
// Kelas Compaq
//===============================================

class Honda extends Laptop {

String nama; //variabel kelas
String nomorSerie;
int kecepatan;

//constuctor kelas
public Compaq (String aNama,String aNomorSerie,int aKecepatan)
{

super("Laptop");
nama = aNama;
nomorSerie = aNomorSerie;
kecepatan = aKecepatan;

}


//Menampilkan Informasi
public void displayData()
{

System.out.println("Nama = "+ this.nama);
System.out.println("Nomor Serie = "+ this.nomorSerie);
System.out.println("Kecepatan maksimum = "+ this.kecepatan);
}

}

//===============================================
// Kelas Pengendali
//===============================================

class LaptopApp
{
public static void main(String[] args)

{

//Mendefinisikan objek dalam kelas

Honda motor1 = new Qompaq("new hard","12345",100);
Honda motor2 = new Acer("Back edition","23456",200);
Honda motor3 = new HP("white clean","34567",300);

//Menampilkan Informasi

laptop1.jenisLaptop();
laptop1.displayData();
System.out.println();

laptop2.jenisLaptop();
laptop2.displayData();

laptop3.jenisLaptop();
laptop3.displayData();

}

}

output :
Nama = compaq
Nomor Serie = 12345
Kecepatan maksimum = 100

Nama = Acer
Nomor Serie = black edition
Kecepatan maksimum = 200
Nama = HP
Nomor Serie = white clean
Kecepatan maksimum = 300



2.Information Hidding And Encapsulation

//Vehicle.java

class Vehicle1{
private double load, maxLoad;
public Vehicle1 (double max){
this.maxLoad = max;
}
public double getLoad(){
return this.load;
}
public double getMaxLoad(){
return this.maxLoad;
}
public boolean addBox(double weight){
double temp = 0.0D;
temp = this.load + weight;
if(temp <= maxLoad){
this.load = this.load + weight;
return true;
}
else{
return false;
}
}
}

//MainVehicle.java

class TestVehicle1{
public static void main(String[] args){
System.out.println("Creating a vehicle with a 10,000 kg maximum load.");
Vehicle1 vehicle = new Vehicle1(10000);
System.out.println("Add box #1 (500kg) : " + vehicle.addBox(500));
System.out.println("Add box #2 (250kg) : " + vehicle.addBox(250));
System.out.println("Add box #3 (5000kg) : " + vehicle.addBox(5000));
System.out.println("Add box #4 (4000kg) : " + vehicle.addBox(4000));
System.out.println("Add box #5 (300kg) : " + vehicle.addBox(300));
System.out.println("Vehicle load is " +vehicle.getLoad() + "kg");
}
}

output :

Add box #1 (500kg) : true
Add box #2 (250kg) : true
Add box #3 (5000kg) : true
Add box #4 (4000kg) : true
Add box #5 (300kg) : false
Vehicle load is 9750.0kg

Tidak ada komentar:

Posting Komentar