0

I'm currently taking a class about design patterns using java. I'm confused by the example code provided for the Interpreter pattern. In the driver class, the main method creates a new instance of the driver class (in order to use the constructor). However, wouldn't the main method in the new instance be called again, creating an infinite loop of new driver classes?

import java.util.Scanner;

public class InterpreterDriver {

    // class variables
    public Conversion originatingContent = null;
    public Expression theExpression = null;

    public InterpreterDriver(Conversion content) {
        originatingContent = content;
    }

    public void interpret(String tString) {

        Scanner in = new Scanner(System.in);
        theExpression = new MapIntToCharacters(tString);
        theExpression.interpret(originatingContent);
    }

    public static void main(String[] args) {
        System.out.println("\n\nCODE INTERPRETER\n");
        System.out.print("Enter your code: ");
        Scanner in = new Scanner(System.in);
        String userInput = in.nextLine();
        System.out.println("Your code: " + userInput);
        Conversion conversion = new Conversion(userInput);
        InterpreterDriver userCode = new InterpreterDriver(conversion);
        userCode.interpret(userInput);
        System.out.println("\n\n");
    }
}
dNillify
  • 13
  • 2

1 Answers1

1

You may be confusing the main method for the constructor. The main method is not called on object instantiation. The constructor method would be called on instantiation:

public InterpreterDriver(Conversion content) {
    originatingContent = content;
}
siralexsir88
  • 418
  • 1
  • 4
  • 14