Make Shape Class The Test Program

Now that I have defined the Circle and Rectangle classes, it's time to test them with a simple program. In Java, the program itself must be another class, and for a standalone Java program, the class must include a public static void method called main (this is akin to the main function in a C program).

The following code shows the MakeShape class (in a file named, which includes a main method to test the geometric shapes:


// Java application to try out various shapes public class MakeShape {

public static void main(String args[]) {

shapes[0] = new Circle(100.0, 100.0, 50.0); shapes[1] = new Rectangle(80., 40., 120., 60.);

System.out.println("\n"+shapes.length+" shapes\n");

double area = shapes[i].computeArea(); System.out.println("Shape #"+i); shapes[i].draw();

System.out.println("Area = "+area); System.out.println("-----------");

The main method creates an array of Shape objects and initializes the array with different shapes. Then, the computeArea and draw methods of each shape are invoked.

You use the new keyword to create instances of objects in Java. There is no corresponding delete or free keyword to get rid of objects when you no longer need them. Instead, Java supports a technique called garbage collection to automatically destroy objects that are no longer needed. (Java keeps track of all references to an object and removes the object when there are no more references to it.) That means you never have to worry about freeing memory in Java. Because memory management is a source of many errors in C and C++ programs, Java's support for garbage collection helps eliminate a major source of potential errors in your applications.

insider insight

In this example, the MakeShape class is the Java application. To compile the program, type the following command:


This step takes care of compiling the file and all the related classes (the,, and files). In other words, the Java compiler (javac) acts a bit like the make utility in UNIX — javac determines the dependencies among classes and compiles all necessary classes.

To run the MakeShape program, use the Java interpreter, as follows:

java MakeShape

The following code shows the result of running the MakeShape program in a terminal window in Linux:

2 shapes Shape #0

Circle of radius 50.0 at (100.0, 100.0) Area = 7853.981633974483

Shape #1

Rectangle with corners (80.0, 40.0) and (120.0, 60.0) Area = 800.0

Was this article helpful?

0 0
Make Money Writing

Make Money Writing

This Report Will Show You How To Make Money By Providing Writing Services To Other Internet Marketers. Learn how to make money by writing the right way. Grab your copy of this report now and learn. Why writing is a great way to earn money. How to compete with cheap writers, even if you charge a lot more money.

Get My Free Ebook

Post a comment