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.
// 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();
}
}
Rectangle Length: 10.0
Rectangle Width: 5.0
Rectangle Area: 50.0
Rectangle
length
and width
.calculateArea()
to compute the area (length × width
).display()
to print rectangle details.RectangleArea
Rectangle
with length 10
and width 5
.display()
method to print the details.✅ 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! 🚀