Refactoring some code with 'instanceof' to overloaded method solution in Java <p>I have this piece of code from GWT in Action:</p> <pre><code>public void processOperator(final AbstractOperator op) { System.out.println("Wordt deze ooit aangeroepen?"); if (op instanceof BinaryOperator) { if ((data.getLastOperator() == null) || (data.isLastOpEquals())) { data.setBuffer(Double.parseDouble(data.getDisplay())); data.setInitDisplay(true); } else { data.getLastOperator().operate(data); } data.setLastOperator(op); } else if (op instanceof UnaryOperator) { op.operate(data); } data.setLastOpEquals(false); } </code></pre> <p>I want to eliminate the 'instanceof' part by using method dispatching:</p> <pre><code>public void processOperator(final BinaryOperator op) { if ((data.getLastOperator() == null) || (data.isLastOpEquals())) { data.setBuffer(Double.parseDouble(data.getDisplay())); data.setInitDisplay(true); } else { data.getLastOperator().operate(data); } data.setLastOperator(op); data.setLastOpEquals(false); } public void processOperator(final UnaryOperator op) { op.operate(data); data.setLastOpEquals(false); } </code></pre> <p>But now I run into trouble in the code below from class ButtonOperator. The following code has AbstractOperator as a type in the constructor. The code for the types UnaryOperator and BinaryOperator would look exactly the same, so it feels a little cumbersome having to make special constructors for them containing the exact same code. What is a better approach? </p> <pre><code>public ButtonOperator(final CalculatorController controller, final AbstractOperator op) { super(op.label); this.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { controller.processOperator(op); } }); this.setStyleName(CalculatorConstants.STYLE_BUTTON); } </code></pre>