Recap - Simple Calculator
Part of the Object Oriented Programming section of Coddy's Java journey — lesson 9 of 87.
Challenge
HardBuild a complete Calculator class that uses all concepts learned:
- Fields: Private fields for
name(String),memory(double),operationCount(int) - Constructors: A parameterized constructor and a default constructor using
this()chaining - this Keyword: Use
thisto assign fields and access them in methods - Getters:
getName(),getMemory(),getOperationCount() - Methods:
add,subtract,multiply,divide,power
The add method stores its result in memory. All methods increment operationCount. The divide method returns 0 if dividing by zero. The power method uses Math.pow().
Try it yourself
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String name = scanner.nextLine();
double num1 = Double.parseDouble(scanner.nextLine());
double num2 = Double.parseDouble(scanner.nextLine());
Calculator calc = new Calculator(name);
System.out.println("Calculator: " + calc.getName());
System.out.println("Memory: " + calc.getMemory());
System.out.println("Add: " + calc.add(num1, num2));
System.out.println("Subtract: " + calc.subtract(num1, num2));
System.out.println("Multiply: " + calc.multiply(num1, num2));
System.out.println("Divide: " + calc.divide(num1, num2));
System.out.println("Divide by zero: " + calc.divide(num1, 0));
System.out.println("Memory: " + calc.getMemory());
System.out.println("Power: " + calc.power(num1, num2));
System.out.println("Operations: " + calc.getOperationCount());
}
}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