Java Tutorials - First Java Program
How to design, develop and execute a program in Java
How to design, develop and execute a program in Java
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
Create a Java program to calculate the perimeter and the area of different shapes
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()
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
Considering the description this is how we could, at first sight, design the 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
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
)
When you define a diagram, ask yourself several questions which can avoid to make costly mistakes :
Now that we have a model, we are ready to define Java classes, how to proceed ?
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;
}
}
This sample class represent the one designed in the class diagram: it has 1 property and 2 methods
You can also notice that :
radius
) are private, while the methods are public: this is
to enforce the principle of encapsulation
double
which is the common
primitive type for numerical data
Math.PI;
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
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
Remember that a constructor takes some parameters which will be used to create a particular instance
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;
}
}
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());
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
The zip of the project is available here geometry