Wednesday, February 9, 2011

Another Java Class with Inheritance

This uses the boat and motorboat classes from the last post. What I have added is a sailboat class that also inherits from boat and added some code to the Program.java file where the main function resides. I am only going to post the changed code here:

SailBoat.java

public class Sailboat extends Boat {
private double mastHeight;
private int numberOfSails;

public void SetMastHeight(double height)
{
mastHeight=height;
}

public double GetMastHeight()
{
return mastHeight;
}

public void SetNumberOfSales(int sails)
{
numberOfSails=sails;
}

public int GetNumberOfSails()
{
return numberOfSails;
}
}

Program.Java

public class Program {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

MotorBoat myBoat=new MotorBoat();
myBoat.setBoatSize(30);
myBoat.setCost(25000);
myBoat.SetHorsePower(20);
double cpf=myBoat.CostPerFoot();


System.out.println("the boat is " + myBoat.getBoatSize()+ " feet long");
System.out.println("the boat costs " + myBoat.getCost() + " dollars");
System.out.println("the horse power is " + myBoat.horsepower );
System.out.println("the cost per foot is " + cpf);

Sailboat myBoat2 = new Sailboat();
myBoat2.setBoatSize(25);
myBoat2.setCost(45000);
myBoat2.SetMastHeight(30);
myBoat2.SetNumberOfSales(2);

System.out.println("*********************************************");
System.out.println("the boat is " + myBoat2.getBoatSize()+ " feet long");
System.out.println("the boat costs " + myBoat2.getCost() + " dollars");
System.out.println("the mast height is " + myBoat2.GetMastHeight() );
System.out.println("the boat has " + myBoat2.GetNumberOfSails() + " sails");
System.out.println("the cost per foot is " + myBoat2.CostPerFoot());

}

}

Here is the output:

the boat is 30 feet long
the boat costs 25000.0 dollars
the horse power is 20.0
the cost per foot is 833.3333333333334
*********************************************
the boat is 25 feet long
the boat costs 45000.0 dollars
the mast height is 30.0
the boat has 2 sails
the cost per foot is 1800.0

No comments:

Post a Comment