w3resource

Java: Abstract Shape3D Class with Sphere and Cube Subclasses

Java Abstract Class: Exercise-6 with Solution

Write a Java program to create an abstract class Shape3D with abstract methods calculateVolume() and calculateSurfaceArea(). Create subclasses Sphere and Cube that extend the Shape3D class and implement the respective methods to calculate the volume and surface area of each shape.

Sample Solution:

Java Code:

//Shape3D.java
abstract class Shape3D {
  public abstract double calculateVolume();

  public abstract double calculateSurfaceArea();
}

//Sphere.java
class Sphere extends Shape3D {
  private double radius;

  public Sphere(double radius) {
    this.radius = radius;
  }

  @Override
  public double calculateVolume() {
    return (4.0 / 3.0) * Math.PI * Math.pow(radius, 3);
  }

  @Override
  public double calculateSurfaceArea() {
    return 4 * Math.PI * Math.pow(radius, 2);
  }
}
//Cube.java
class Cube extends Shape3D {
  private double sideLength;

  public Cube(double sideLength) {
    this.sideLength = sideLength;
  }

  @Override
  public double calculateVolume() {
    return Math.pow(sideLength, 3);
  }

  @Override
  public double calculateSurfaceArea() {
    return 6 * Math.pow(sideLength, 2);
  }
}
//Main.java
public class Main {
  public static void main(String[] args) {
    Shape3D sphere = new Sphere(7.0);
    Shape3D cube = new Cube(6.0);

    System.out.println("Sphere Volume: " + sphere.calculateVolume());
    System.out.println("Sphere Surface Area: " + sphere.calculateSurfaceArea());

    System.out.println("Cube Volume: " + cube.calculateVolume());
    System.out.println("Cube Surface Area: " + cube.calculateSurfaceArea());
  }
}

Sample Output:

Sphere Volume: 1436.7550402417319
Sphere Surface Area: 615.7521601035994
Cube Volume: 216.0
Cube Surface Area: 216.0

Explanation:

In the above exercise -

  • The abstract class "Shape3D" has two methods calculateVolume() and calculateSurfaceArea(). The subclasses 'Sphere' and 'Cube' extend the Shape3D class and provide their own implementations for these abstract methods.
  • The "Sphere" class calculates the volume and surface area of a sphere using the given radius, while the Cube class calculates the volume and surface area of a cube using the given side length.
  • In the main method, we create instances of Sphere and Cube. We then call the calculateVolume() and calculateSurfaceArea() methods on each object to calculate and display the respective volume and surface area.

Flowchart:

Flowchart: Shape3D Java
Flowchart: Sphere Java
Flowchart: Cube Java
Flowchart: Main Java

Java Code Editor:

Contribute your code and comments through Disqus.

Previous: Abstract Employee class with Manager and Programmer subclasses.
Next: Java: Abstract Vehicle Class with Car and Motorcycle Subclasses.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.