Search code examples
javainheritanceextendsuperclasssuper

Super thinks it is not the first constructor in a statement


I can't seeem to get this code to work. I have several different classes listed out, and they extend each other. The code for the box super, however, tends to not think it is the first constructor.

 public class Rectangle3
 {
// instance variables 
private int length;
private int width;

/**
 * Constructor for objects of class rectangle
 */
public void Rectangle(int l, int w)
{
    // initialise instance variables
    length = l;
    width = w;
}

// return the height
public int getLength()
{
    return length;
}
public int getWidth()
{
    return width;
}

}

Then the next one

 public class Box3 extends Rectangle3
{
// instance variables 
private int height;

/**
 * Constructor for objects of class box
 */
public void Box(int l, int w, int h)
{
    // call superclass
    super (l, w);
    // initialise instance variables
    height = h;
}

// return the height
public int getHeight()
{
    return height;
}

}

then the cube...

public class Cube3 extends Box3
{
   //instance variable
private int depth;

/**
 * Cube constructor class
 */   
    public void Cube(int l, int w, int h, int d)
   {
   //super call
   super(l, w, h);
   //initialization of instance variable
   depth = d;
}

//return call to depth
public int getDepth()
{
    return depth;
}

}


Solution

  • Your code doesn't have constructors defined. The method public void Box(int l, int w, int h) is not a constructor for a Box3 class, and therefor use of super(..) is invalid. The same goes for the methods public void Cube(int l, int w, int h, int d) and public void Rectangle(int l, int w)

    Instead you need to define a constructor in Box3:

    public Box3(int l, int w, int h) {
        // call superclass
        super (l, w);
        // initialise instance variables
        height = h;
    }
    

    Notice the lack of void and the fact its name is identical to the class name.

    Note that the above constructor will not work, because Rectangle3 doesn't have this constructor. So for Rectangle3 you need to use:

    public Rectangle3(int l, int w) {
        // initialise instance variables
        length = l;
        width = w;
    }
    

    And the same goes for Cube3:

    public Cube3(int l, int w, int h, int d) {
        //super call
        super(l, w, h);
        //initialization of instance variable
        depth = d;
    }
    

    See also the Java Tutorial "Providing Constructors for Your Classes".