Credits

Saturday, January 2, 2010

Java's Polymorphism

Polymorphism principle allows the taking of  several forms for an object. 

Do check sample application.



[+/-] show/hide



public class Bicycle {

// the Bicycle class has three fields
public int cadence;
public int gear;
public int speed;

// the Bicycle class has one constructor
public Bicycle(int startCadence, int startSpeed, int startGear) {
gear = startGear;
cadence = startCadence;
speed = startSpeed;
}

// the Bicycle class has four methods
public void setCadence(int newValue) {
cadence = newValue;
}

public void setGear(int newValue) {
gear = newValue;
}

public void applyBrake(int decrement) {
speed -= decrement;
}

public void speedUp(int increment) {
speed += increment;
}
//the newly added method
public void printDescription(){
System.out.println("\nBike is in gear " + this.gear + " with a cadence of " +
this.cadence + " and travelling at a speed of " + this.speed + ". ");
}

}


public class MountainBike extends Bicycle{
private String suspension;

public MountainBike(int startCadence, int startSpeed, int startGear, String suspensionType){
super(startCadence, startSpeed, startGear);
this.setSuspension(suspensionType);
}

public String getSuspension(){
return this.suspension;
}

public void setSuspension(String suspensionType){
this.suspension = suspensionType;
}

public void printDescription(){
super.printDescription();
System.out.println("The MountainBike has a " + getSuspension()
+ " suspension.");
}
}

// create the RoadBike class. Because road or racing bikes have skinny tires, add an attribute to track the tire width. Here is the RoadBike class:

public class RoadBike extends Bicycle{
private int tireWidth; // In millimeters (mm)

public RoadBike(int startCadence, int startSpeed, int startGear, int newTireWidth){
super(startCadence, startSpeed, startGear);
this.setTireWidth(newTireWidth);
}

public int getTireWidth(){
return this.tireWidth;
}

public void setTireWidth(int newTireWidth){
this.tireWidth = newTireWidth;
}

public void printDescription(){
super.printDescription();
System.out.println("The RoadBike has " + getTireWidth()
+ " MM tires.");
}

}



AddThis