In this example, we will create a Java program to calculate the volume of a cube using Object-Oriented Programming (OOP) principles.
✅ Encapsulation: We store the cube’s side length as a private attribute.
✅ Constructors: Initialize values when creating an object.
✅ Methods: Provide a function to calculate and return the volume.
This structured approach ensures data security, code reusability, and ease of maintenance.
// Class to represent a Cube
class Cube {
// Private attribute for encapsulation
private double side;
// Constructor to initialize the cube's side length
public Cube(double side) {
this.side = side;
}
// Method to calculate the volume of the cube
public double calculateVolume() {
return Math.pow(side, 3); // side³
}
// Method to display cube details
public void display() {
System.out.println("Cube Side Length: " + side);
System.out.println("Cube Volume: " + calculateVolume());
}
}
// Main class to run the program
public class CubeVolume {
public static void main(String[] args) {
// Creating a cube object with side length = 4
Cube cube = new Cube(4);
// Displaying cube details and volume
cube.display();
}
}
Cube Side Length: 4.0
Cube Volume: 64.0
Cube
side
to store the cube’s side length.side
.calculateVolume()
to compute the volume using side³ (Math.pow(side, 3)
).display()
to print cube details.CubeVolume
Cube
with a side length of 4
.display()
method to print the details and volume.✅ Encapsulation – Protects cube attributes.
✅ Modularity – Easy to extend with more methods (e.g., surface area calculation).
✅ Reusability – The Cube
class can be used across different programs.
This Java program demonstrates clean, structured OOP design, making it efficient, reusable, and scalable! 🚀