Java Code Example: Volume of a Cube

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.


Java Code Example:

// 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();
    }
}

Expected Output:

Cube Side Length: 4.0
Cube Volume: 64.0

Code Explanation:

  1. Class Cube
    • Defines a private attribute side to store the cube’s side length.
    • Uses a constructor to initialize the value of side.
    • Implements calculateVolume() to compute the volume using side³ (Math.pow(side, 3)).
    • Implements display() to print cube details.
  2. Main Class CubeVolume
    • Creates an object of Cube with a side length of 4.
    • Calls the display() method to print the details and volume.

Why Use OOP for This?

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! 🚀