Please disable adblock to view this page.

← Go home

Nested (Inner) Anonymous Classes in Java

java-display

May 2, 2017
Published By : Pratik Kataria
Categorised in:

Let’s see the Code

import java.util.Scanner;

public class Calculator {

	public static void main( String[] args ){
		Calculator c = new Calculator();
		c.calculate();
	}
	
	protected void calculate() {
		InputHelper helper = new InputHelper();
		String s1 = helper.getInput("Enter a number: ");
		String s2 = helper.getInput("Enter a number: ");
		String op = helper.getInput("Choose an operation (+ - * /): ");

		double result = 0;

		try {
			switch(op) {
				case "+":
					result = MathHelper.addValues(s1, s2);
					break;
				case "-":
					result = MathHelper.subtractValues(s1, s2);
					break;
				case "*":
					result = MathHelper.multiplyValues(s1, s2);
					break;
				case "/":
					result = MathHelper.divideValues(s1, s2);
					break;
				default:
					System.out.println("Invalid operation");
					return;
			}
			System.out.println("The result is: " +result);
		} catch( Exception e ) {
			System.out.println("Number formatting expression: " + e.getMessage());
		}
	}

	class InputHelper {
		private String getInput( String prompt ) {
			System.out.print(prompt);
			Scanner sc = new Scanner(System.in);
			return sc.nextLine();
		}
	}
}

 

public class MathHelper {
	public static double addValues(String s1, String s2) {
		double d1 = Double.parseDouble(s1);
		double d2 = Double.parseDouble(s2);
		return d1 + d2;
	}

	public static double subtractValues(String s1, String s2) {
		double d1 = Double.parseDouble(s1);
		double d2 = Double.parseDouble(s2);
		return d1 - d2;
	}
	public static double multiplyValues(String s1, String s2) {
		double d1 = Double.parseDouble(s1);
		double d2 = Double.parseDouble(s2);
		return d1 * d2;
	}
	public static double divideValues(String s1, String s2) {
		double d1 = Double.parseDouble(s1);
		double d2 = Double.parseDouble(s2);
		return d1 / d2;
	}

}

Notes:

  • MathHelper’s all methods are public.
  • Protected denotes the class which can be used by any other class within the same package.
  • Calculator c = new Calculator() -> creates an instance of the class
  • Above instantiation calls the Calculator() constructor which we haven’t defined. That’s okay since Java creates a no argument constructor automatically.
  • If we had protected static void calculate(), we could directly call the calculate() method.
  • class InputHelper is the nested class. Thus, getInput() is an instance method of InputHelper class.
  • For instance method, we need to created instance. Thus, InputHelper helper = new InputHelper();
  • Being a nested class, it is available to only Calculator class since that is where it is defined.
  • getInput() is marked private but it can be called because it is in the same code file as Calculator class.
Pratik Kataria is a budding programmer, web designer and developer.