Java Puzzle #9: Template method pattern

The following Java Puzzle is an example for the template method pattern. It is a design pattern by the Gang of Four.

What is the output of the following snippet: AbstractClass.java:

public class AbstractClass {
    int templateMethod() {
        return simpleOperation1() * simpleOperation2();
    }

    int simpleOperation1() {
        return 2;
    }

    int simpleOperation2() {
        return 3;
    }
}

ConcreteClass.java:

public class ConcreteClass extends AbstractClass {
    @Override
    int simpleOperation1() {
        return 5;
    }

    @Override
    int simpleOperation2() {
        return 7;
    }
}

test.java:

public class test {
    public static void main(String[] args) {
        ConcreteClass t = new ConcreteClass();
        System.out.println(t.templateMethod());
    }
}

. . . . . . . . . . . . . . . . .

Answer

35

35

Explanation

You can think of it like this: First, you create the empty class ConcreteClass. It has only the methods inherited by Object like the constructor, equals() and toString(). Then it gets extended by AbstractClass with templateMethod(), simpleOperation1() and simpleOperation2(). After that, the method overrides simpleOperation1() and simpleOperation2(), but templateMethod() uses them. It uses the methods that are now in ConcreteClass.

I don't know what Java exactly does internally, but thats a good way to think about it. If somebody has more information, please share it as a comment!

Leave a Reply

comments powered by Disqus