Recap - Shape Calculator
Part of the Object Oriented Programming section of Coddy's Java journey — lesson 33 of 87.
Challenge
EasyLet's build a shape calculator that brings together all the polymorphism concepts you've learned in this chapter. You'll create an abstract Shape class with concrete subclasses, then use polymorphism to calculate and display areas uniformly.
You'll organize your code across four files:
Shape.java: Create an abstract class that serves as the foundation for all shapes. Every shape has anamefield (String). Include a constructor to initialize it, a getter methodgetName(), and an abstract methodgetArea()that returns a double. Also add a methoddescribe()that returns:[name]: [area](where area is formatted to 2 decimal places usingString.format("%.2f", getArea())).Circle.java: Create a concrete class that extends Shape. Circles have aradiusfield (double). Usesuperto pass "Circle" as the name. ImplementgetArea()to return the area usingMath.PI * radius * radius.Rectangle.java: Create another concrete class that extends Shape. Rectangles havewidthandheightfields (both double). Pass "Rectangle" as the name to the parent constructor. ImplementgetArea()to return width multiplied by height.Main.java: Build a shape calculator that demonstrates polymorphism in action. You'll receive three inputs: a radius for the circle, a width, and a height for the rectangle.Create a Circle and a Rectangle, then store them in an array of
Shapereferences. Loop through the array and for each shape, print its description using thedescribe()method.After the loop, calculate and print the total area of all shapes with the format:
Total area: [sum](also formatted to 2 decimal places). Use a separate loop or accumulator to sum the areas by callinggetArea()on each shape reference.
You will receive three inputs: the circle's radius (double), the rectangle's width (double), and the rectangle's height (double).
Your output should show three lines - one description for each shape followed by the total area. Notice how you can treat different shapes uniformly through the abstract Shape type while each shape calculates its area in its own way!
Try it yourself
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Read inputs
double radius = scanner.nextDouble();
double width = scanner.nextDouble();
double height = scanner.nextDouble();
// TODO: Create a Circle object using the radius
// TODO: Create a Rectangle object using width and height
// TODO: Create an array of Shape references and store both shapes in it
// TODO: Loop through the array and print each shape's description using describe()
// TODO: Calculate the total area of all shapes
// Use a loop or accumulator to sum the areas by calling getArea() on each shape
// TODO: Print the total area with format: "Total area: [sum]"
// Use String.format("%.2f", totalArea) for formatting
}
}
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesIntroduction to OOPClasses vs ObjectsThe this KeywordMethodsFields (Attributes)Constructor MethodConstructor OverloadingRecap - Simple Calculator4Inheritance
Basic Inheritance (extends)The super KeywordMethod Overriding (@Override)Constructor ChainingThe Object ClassSingle & Multilevel InheritWhy No Multi Class InheritRecap - Employee Hierarchy7Special Methods & Object Class
toString() Methodequals() and hashCode()clone() MethodcompareTo() and ComparableComparator InterfaceRecap - Custom Sorting2Access Modifiers & Encapsulate
Access Levels OverviewGetter and Setter MethodsInformation HidingThe final KeywordRecap - Bank Account Manager5Polymorphism
Method Overloading BasicsMethod Overriding (Run-Time)Upcasting and DowncastingThe instanceof OperatorAbstract Classes and MethodsRecap - Shape Calculator8Advanced OOP Concepts
Composition vs InheritanceAggregation vs CompositionInner Nested & Anonymous ClassEnums and Enum MethodsRecords (Java 16+)Sealed Classes (Java 17+)3Class Props & Static Member
Instance vs Static VariablesStatic MethodsStatic BlocksConstants (static final)Recap - Counter & Utility6Interfaces & Abstract Classes
Introduction to InterfacesImplementing InterfacesMulti Interface ImplemenDefault & Static in InterfaceAbstract Classes vs InterfacesFunctional InterfacesRecap - Payment System