- Java
- OOP
- BlueJ
- Rebuilt
OOP Calculator (Java)
Functional calculator in Java applying encapsulation and inheritance. Clean structure for future features and UI improvements.
The calculator below is a JavaScript port of the Java classes, so it runs in your browser. The Java version, with a Swing interface and tests, is in the code.
0
Keyboard works too: 0–9 + − * / Enter ⌫ Esc
History
Calculations you finish with = appear here.
How it’s built
«abstract»Operation
- Addition
- Subtraction
- Multiplication
- Division
Calculator holds an Operation and calls apply(), without knowing which subclass it is.
- Inheritance: each operation extends the abstract
Operationclass and supplies its own symbol andapply()method. Adding a new operation means adding a subclass, without changing the calculator. - Encapsulation:
Calculatorkeeps its state in private fields. The interface can only press keys and read the display, so the state can’t become inconsistent. - Separation of concerns: the Swing
CalculatorPanel(and this web page) only forward key presses, so the user interface can be replaced without touching the arithmetic. - Tested: the same behaviours are checked in Java (
CalculatorTest) and JavaScript, including left-to-right chaining, rounding and division by zero.