I am doing the following exercise:
a) Create a base class named Rectangle that contains length and width data members. From this class, derive a class named Box having an additional data member named depth. The method members of the base Rectangle class should consist of a constructor and have an area( ) method. The derived Box class should have a constructor and an override method named area( ) that returns the surface area of the box and a volume( ) method.
b) Include the classes constructed for Exercise 8a in a working Java program. Have your program call all of the member methods in each class and explain the result when the area method is called using two Box objects.
I have 3 separate files : Rectangle.java, Box.java, and UsingShapes.java
This is what I have so far:
Rectangle.java
Code:
public class Rectangle
{
protected double length;
protected double width;
public Rectangle (double lh, double wh)
{
length = lh;
width = wh;
}
public double area()
{
return(length * width);
}
}
Box.java
Code:
public class Box {
protected double depth;
public Box (double lh, double wh, double dh)
{
super(lh);
super(wh);
depth = dh;
}
public double area()
{
return ((2*super.area)+(2*(dh*super(lh))+ (2*(dh*super(wh))))); //surface area of box = 2(h*w) + 2(h*l) + 2(w*l)
}
public double volume()
{
return (depth * super.area());
}
}
UsingShapes.java (File which runs the other 2 files)
Code:
public class UseShapes {
public static void main (String[] args) {
Rectangle rect1 = new Rectangle(2,4);
Box bv = new Box(5,5,5);
Box boxOne = new Box(1, 2, 3);
Box boxTwo = new Box(4, 5, 6);
System.out.println("The area of the rectangle is " + rect1.area);
System.out.println("The volume of the box is " + bv.volume);
System.out.println("The surface area of boxOne is " +boxOne.area);
System.out.println("The surface area of boxTwo is " +boxTwo.area);
}
}
ANy suggestions for changes / additions? Thanks!
