-4

How can I create a Rectangle object and use its methods to determine the area?

I have tried to create a Rectangle object and print it to console like this:

import java.awt.Rectangle;

public class Rectangle
{   
    public static void main(String []args)
    {
        Rectangle box = new Rectangle(5,10,20,30);
        System.out.println(box);            
    }
}

I expected it to print the area but it doesn't. What am I doing wrong?

trooper
  • 4,444
  • 5
  • 32
  • 32
Java_NewBie
  • 93
  • 1
  • 10

1 Answers1

0

If you look at the code for Rectangle.toString(), which is called automatically by System.out.println, you will see that it prints out the parameters that make up the Rectangle object. However, it will not draw it:

return getClass().getName() + "[x=" + x + ",y=" + y + ",width=" + width + ",height=" + height + "]";

You're not explicitly calling toString(), but impliclty you are:

Ankur Singhal
  • 26,012
  • 16
  • 82
  • 116