I am trying to understand how packages work. I think I have finished steps 1-7 but I am not sure. Now I am trying to start step 8 however I am confused as to how I can get the Test class to use the squar and cube classes. How does the code even start?

1.Create a class named Square that contains only two data fields that contain the height and width . You must declare these fields as ‘private’.
2.The constructor should take parameters to initialize height and width.
3.Write a method named computeSurfaceArea() that calculates and returns the surface area of the square based on the height and width fields.
4.Save this class as Square.java
5.Create a class named Cube that contains a private field called depth. This class should be a subclass (extends) of the Square class. The constructor should take three parameters used to initialize the base class and it’s own ‘depth’ member field.
6.Create a method named computeSurfaceArea() that calculates the surface area of the cube. This method should override the parent method. This method should return the surface are of the cube (width x height x depth). You may not directly access the height and width fields of the parent class.
7.Save this class as Cube.java
8.Create a class called Test that instantiates a square and a cube and then displays the surface area of each one. The display code should be in this class. There should be no display code in the Square or Cube class methods.
9.Save this class as Test.java

My code so far:

package square;

public class Square
{
    private int height;
    private int width;

    publicSquare(int x, int y)
    {
        height = x;
        width = y;
    }

    public int computeSurfaceArea()
    {
        return height * width;
    }


}





package square;

public class Cube extends Square
{
    private int depth;

    public Cube(int x, int y, int z)
    {
        height =x;
        width = y;
        depth = z;
    }

    public int computeSurfaceArea()
    {
        return height*width*depth;
    }

}

Am I doing this correctly or is it wrong?

Recommended Answers

All 2 Replies

what exactly has this got to do with packages?
your constructor needs a space between public and Square
looks like you are accessing the Square variables directly, so maybe re-think that.
for instance: your method to calculate, you could do something like this:

public int computeSurfaceArea(){
return depth*super.computeSurfaceArea();
}

and a bit the same for the constructor.

do you have any trouble with the later parts?

I was able to find and fix my mistakes. The program now runs the way I need it to run.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.