Jumat, 10 Mei 2013

polymorphism

23.17

Share it Please
                Polimorfisme (polymophism) atau yang disebut juga dengan kebanyak rupaan adalah kemampuan program untuk mengungkap banyak hal berbeda dengan cara yang sama. Polimorphisme adalah konsep yang sangat handal bagi pengembang perangkat lunak untuk pemisahan secara jelas diantara sub sistem yang berbeda. Dengan dimikian sebuah sistem akan bisa dimodifikasi secara mudah karena hanya dibutuhkan interface antar class.

Bicycle.java
public class Bicycle {
public int gear;
public int speed;
public int power;
public Bicycle(int startGear, int startSpeed, int startPower)
{
gear = startGear;
speed = startSpeed;
power = startPower;
}
public void setPower( int newValue)
{
power = newValue;
}
public void setGear( int newValue)
{
gear = newValue;
System.out.println(“Gear At”+ gear);
}
public void applyBreake(int decrement )
{
speed -= decrement;
}
public void speedUp(int increment)
{
speed += increment;
}
public void printDescription()
{
System.out.println(“Bike in gear”+this.gear+”with power”+this.power+”and speed”+this.speed);
}
}

MountainBike.java
public class MountainBike extends Bicycle {
private String suspension;
public MountainBike(int startSpeed, int startGear, int startPower, String startSuspension )
{
super(startGear, startSpeed, startPower);
setSuspension(startSuspension);
}
public String getSuspension(){
return this.suspension;
}
public void setSuspension(String suspensionType){
this.suspension = suspensionType;
}
@Override
public void printDescription(){
super.printDescription();
System.out.println(“The MountainBike has a ” + getSuspension()
+ ” suspension.”);
}
}

RoadBike.java
public class RoadBike extends Bicycle {
private int tireWidth;
public RoadBike(int startSpeed, int startPower, int startGear, int newTireWidth)
{
super(startGear, startSpeed, startPower);
setTireWidth( newTireWidth);
}
public int getTireWidth(){
return this.tireWidth;
}
public void setTireWidth(int newTireWidth){
this.tireWidth = newTireWidth;
}
@Override
public void printDescription(){
super.printDescription();
System.out.println(“The RoadBike has ” + getTireWidth()
);
}
}

Main.java
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Bicycle bike01, bike02, bike03;
bike01 = new Bicycle(20, 10, 1);
bike02 = new MountainBike(20, 10, 5, “Dual”);
bike03 = new RoadBike(40, 20, 8, 23);
MountainBike Ren = new MountainBike(99,9,9,”Dual”);
bike01.printDescription();
bike02.printDescription();
bike03.printDescription();
}
}


semoga bermanfaat. :)

0 komentar:

Posting Komentar