Introduction

This tutorial aims at showing you how to develop your first java program. The exercise is extracted from one of our lectures. It gives you a complete example on how to proceed

Exercise description

Exercise

Create a Java program to calculate the perimeter and the area of different shapes

  • A triangle
  • A circle
  • A square
And display those results in the standard output

Find a model

The exercise subject is pretty vague concerning the model of the program. What we can identify is that there are at least 3 concepts : the Triangle, Circle, Square concepts.

Those concepts seem to have at least 2 methods: the calculateArea() and calculatePerimeter()

Note

When you have to realize a program, it is recommended to not program before having carefully understood what are the program features.

Try to have a reflexion phase (even if is not by writing down your ideas) before to start the development

Model

Considering the description this is how we could, at first sight, design the class diagram :

Possible class diagram

Notice that shapes have all specific properties, which are mandatory to calculate the area or the perimeter of the shape. Sometimes those properties are not specified in the feature description

Diagram discussion

This conception is not optimal, why?

  • Because the shapes could inherit from one generic shape allowing to predefine the behaviour of inheriting shapes. This is the concept of Interface, we will see it further during this course

  • We can also want to factor the best we can the treatments relative to the calculus for a kind of shape This for instance obvious for the Square shape

    To foresee the evolution of the program, it would be convenient to define a Quadrilateral generic class, to allow a better re-usability of the general perimeter and area formula

    The fact to consider that a Square is-aQuadrilateral, implies the disappearance of the side property (because in a square the height and width are equal, but not necessarily in every Quadrilateral)

Note

When you define a diagram, ask yourself several questions which can avoid to make costly mistakes :

  • Did I list all the properties and methods of the described objects ?
  • Does the defined objects will help me to answer easily to the requested feature?
  • Does my program will evolve ?
  • If the answer is yes, will my conception be favorable to that evolution?

Retained diagram

The retained class diagram

From Model to Java Code

Now that we have a model, we are ready to define Java classes, how to proceed ?

Class definition in Java

package fr.tbr.exercises.geometry; //always define a significant package

/**
 * Define a Circle class, which has 2 methods for calculating its perimeter and area
 * @author Tom
 *
 */
public class Circle {

	//the way to define a constant : static final
	private static final double PI = 3.14159;

	//this is the radius of the circle
	private double radius;

	/**
	 * compute the area of the circle
	 * @return the area
	 */
	public double getArea(){
		return PI * radius * radius;
	}

	/**
	 * compute the perimeter of the circle
	 * @return the perimeter
	 */
	public double getPerimeter(){
		return 2 * PI * radius;
	}
}

Remarks

This sample class represent the one designed in the class diagram: it has 1 property and 2 methods

You can also notice that :

  • The properties (here the radius) are private, while the methods are public: this is to enforce the principle of encapsulation
  • The manipulated numerical data are of type double which is the common primitive type for numerical data
  • I defined a constant named PI, to represent the π constant. There is a dedicated constant for that in the java language Math.PI;

Use this class in Java

In the preceding example, the class is only defined, there is no way to use it

To use this class definition, you should be able to instantiate it, you must define a constructor

About the instantiation process

The difference between a class and its instances is that a class has no substantial existence, it's just a schema of construction. Instances though, are the result of the construction.

Constructors are the factory that allows to create instances that enforce the schema

In the schema above, the analogy between the instantiation mechanism and a car factory

Remember that a constructor takes some parameters which will be used to create a particular instance

Define a constructor

A constructor is a particular method of the class, it has no return type and its name is the class name. As for the other entities composing a class (method or property), you can define an access level.

Like methods, it is possible to pass parameter to initialize the newly created instance

/**
 * The constructor to create a circle with a radius equal to the given parameter
 * @param r the radius of the circle to be created
 */
public Circle(double r){
    this.radius = r;
}

Notice the this keyword, this keyword indicate that you manipulate the property of the current instance.

Use the this keyword

The use of the this keyword is highly recommended since it avoids the confusion between method local variables and class properties

Hereafter, the code, completed with the constructor definition, and improved with the this usage

package fr.tbr.exercises.geometry;

/**
 * Define a Circle class, which has 2 methods for calculating its perimeter and area
 * @author Tom
 *
 */
public class Circle {

	//the way to define a private constant : private static final
	private static final double PI = Math.PI;

	//this is the radius of the circle
	private double radius;

	/**
	 * The constructor to create a circle with a radius equal to the given parameter
	 * @param r the radius of the circle to be created
	 */
	public Circle (double r){
		this.radius = r;
	}

	/**
	 * compute the area of the circle
	 * @return the area
	 */
	public double getArea(){
		return PI * this.radius * this.radius;
	}

	/**
	 * compute the perimeter of the circle
	 * @return the perimeter
	 */
	public double getPerimeter(){
		return 2 * PI * this.radius;
	}
}   

Instantiate and use the class

To be able to use the Circle class, you have to call the constructor. Like hereafter, you can call it in the part of your program requiring the Circle class

Circle smallCircle = new Circle(20);
Circle bigCircle = new Circle(60);

System.out.println("Small circle perimeter : " + smallCircle.getPerimeter() + ", area : " + smallCircle.getArea());
System.out.println("Big circle perimeter : " + bigCircle.getPerimeter() + ", area : " + bigCircle.getArea());

Program execution

To run a program in java, you must provide a main method. The main method defines an entry point in your program, that allows the JVM to start a new execution

It is recommended that you put the main method in a dedicated class, so there is no pollution in your functional class. That's why we will create a class named Geometry

package fr.tbr.exercises.geometry;

public class Geometry {

 public static void main(String[] args) {
   Circle smallCircle = new Circle(20);
   Circle bigCircle = new Circle(60);

   System.out.println("Small circle perimeter : " + smallCircle.getPerimeter() + "...");
   System.out.println("Big circle perimeter : " + bigCircle.getPerimeter() + "...");

  }
} 

generates the output :

Small circle perimeter : 125.66370614359172, area : 1256.6370614359173
Big circle perimeter : 376.99111843077515, area : 11309.733552923255
 

Resources

The zip of the project is available here geometry