Java Code Example: Area of ​​a Rectangle

In this example, we will create a Java program to calculate the area of a rectangle using Object-Oriented Programming (OOP) principles.

Encapsulation: We store the rectangle’s length and width as private attributes.
Constructors: Initialize values when creating an object.
Methods: Provide a function to calculate and return the area.

This approach ensures data protection, code reusability, and scalability for future enhancements.


Java Code Example:

// Class to represent a rectangle
class Rectangle {
    // Private attributes for encapsulation
    private double length;
    private double width;

    // Constructor to initialize the rectangle dimensions
    public Rectangle(double length, double width) {
        this.length = length;
        this.width = width;
    }

    // Method to calculate the area of the rectangle
    public double calculateArea() {
        return length * width;
    }

    // Method to display the rectangle details
    public void display() {
        System.out.println("Rectangle Length: " + length);
        System.out.println("Rectangle Width: " + width);
        System.out.println("Rectangle Area: " + calculateArea());
    }
}

// Main class to run the program
public class RectangleArea {
    public static void main(String[] args) {
        // Creating a rectangle object with length = 10 and width = 5
        Rectangle rect = new Rectangle(10, 5);

        // Displaying rectangle details and area
        rect.display();
    }
}

Expected Output:

Rectangle Length: 10.0
Rectangle Width: 5.0
Rectangle Area: 50.0

Code Explanation:

  1. Class Rectangle
    • Defines two private attributes: length and width.
    • Uses a constructor to initialize these values.
    • Implements calculateArea() to compute the area (length × width).
    • Implements display() to print rectangle details.
  2. Main Class RectangleArea
    • Creates an object of Rectangle with length 10 and width 5.
    • Calls the display() method to print the details.

Why Use OOP for This?

Encapsulation – Keeps data secure.
Modularity – Easy to extend with more features (e.g., perimeter calculation).
Reusability – The Rectangle class can be used in different programs.

This Java program demonstrates clean, structured OOP design, making it efficient and reusable! 🚀