Start New Discussion within our Software Development Community

I have the following program written where Square extends Rectangle. I cannot figure out how to get the correct display for the x and y coordinates. It should display
Expected: Square[x=5, y=5, width=30, height=30] but instead it displays Square[x=10,y=20,width=30,height=30].

import java.awt.Rectangle;

public class Square extends Rectangle 
{
        private int side;
        private int x;
        private int y;
        
        public Square(int xcoord, int ycoord, int sideLength) 
        {
        	super(xcoord, ycoord, sideLength, sideLength);
        	x = xcoord;
        	y = ycoord;
                side = sideLength;
                Rectangle Square = new Rectangle();
                Square.setLocation(xcoord-15, ycoord-15);
                Square.setSize(sideLength, sideLength);
        }
        
        public void toString(int xcoord, int ycoord)
        {
        	setLocation(xcoord-15, ycoord-15);
            super.setLocation(x,y);
        }
        
        public int getArea()
        {
                int Area = side * side;
                return Area;
        }
}
public class SquareTester
{
	public static void main(String[] args)
	{
		Square sq = new Square(10, 20, 30);
		
		System.out.println(sq.toString());
		System.out.println("Expected: Square[x=5, y=5, width=30, height=30]");
		System.out.println("Area: " + sq.getArea());
		System.out.println("Expected: 900");

	}

}

This is the output you are getting from running SquareTester

Square[x=10,y=20,width=30,height=30]
Expected: Square[x=5, y=5, width=30, height=30]
Area: 900
Expected: 900

You can get your expected output by passing 5,5,30 to the Square constructor.

Square sq = new Square(5, 5, 30);

NOTE :
Your toString method, which is

public void toString(int xcoord, int ycoord)

is not the correct overriding of the,

public String toString()
This article has been dead for over six months. Start a new discussion instead.