• Martin Thoma
  • Home
  • Categories
  • Tags
  • Archives
  • Support me

Java Puzzle #9: Template method pattern

Contents

  • Answer
  • Explanation

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!

Published

Aug 10, 2012
by Martin Thoma

Category

Code

Tags

  • Design Pattern 2
  • Java 36
  • Programming 52
  • puzzle 22
  • SWT I 9

Contact

  • Martin Thoma - A blog about Code, the Web and Cyberculture
  • E-mail subscription
  • RSS-Feed
  • Privacy/Datenschutzerklärung
  • Impressum
  • Powered by Pelican. Theme: Elegant by Talha Mansoor