Create a new Java Class Rectangle – This Python Tutorial will explain the creation of a new Java class named Rectangle with the following class specification:
How To Create a New Rectangle Class in Java
- Write a Java program using Objects and Classes concepts in Object Oriented Programming. Define the Rectangle class that will have:
- Two member variables width and height ,
- A no-arg constructor that will create the default rectangle with width = 1 and height =1.
- A parameterized constructor that will create a rectangle with the specified x, y, height and width.
- A method getArea() that will return the area of the rectangle.
Note: Formula for area of rectangle is (width x height)
Formula for perimeter of rectangle is: 2 x (width+height)
A method getPerimeter() that will return the perimeter of the rectangle.
Write a test program that creates two rectangle objects. It creates the first object with default values and the second object with user specified values. Test all the methods of the class for both the objects.
How to Calculate Area and Perimeter in Rectangle Class
Formula for Area of a Rectangle
To calculate area of triangle, we need the number of square units to cover the surface of a figure.
Hence, the formula is: Area = Length x Width
Formula for perimeter of Rectangle
The perimeter may be defined as the distance around a figure.
Hence formula is:
Perimeter of Rectangle = 2 x Length + 2 x Width
Perimeter of Rectangle = 2 (Length + Width)
The Source Code of Java Rectangle Class Program
The output of a sample run of the Java Program
Area of first object=1.0 Perimeter of first object=4.0 Area of second object=120.0 Perimeter of second object=46.0
9,371 total views, 5 views today