Template Method Pattern slide HashTable

Moderatoren: pmueller, SE - Design and Construction

Beiträge: 1
Registriert: 6. Jul 2018 11:00

Template Method Pattern slide HashTable

Beitrag von moesta »


on slide 8 (last slide) of the template method pattern, there is an example given of the HashTable trait in Scala.

The class documentation states that the two parameter initialSize and loadfactor may be overwritten in class HashTable.

How would that look like?

Because overwriting the values in an extending class would not work as intended as the constructor of HashTable would be called first and create the Array table with initialSize=16, right?

Would you have to use early definition for this?

As for the question why a method is better i would assume that the trait constructor would call the overwritten initialSize method instead of its own, correct?


Beiträge: 87
Registriert: 25. Jan 2018 11:14

Re: Template Method Pattern slide HashTable

Beitrag von pmueller »


no HashTable does not have a real superclass constructor since it is a trait.
Here is small example to illustrate this:

Code: Alles auswählen

trait Test {

  def constant = 1

  var array = new Array(constant)


class Implementer extends Test {

  override def constant = 2
The compiled Java Bytecode reconverted to Java looks (more or less - I omitted a little bit of reflection and the default method stuff) like the following:

Code: Alles auswählen

interface Test {
	public static int constant$(Test test) {
	public int constant() {
		return 1;
	public Object[] array(); // abstract must be implemented 
	public void array_$eq(Object[] array); // abstract must be implemented 
  	public static void $init$(Test test) {
public class Implementer implements Test {\
	Object[] array;
	public 	Object[] array() {
		return array;
	public void array_$eq(Object[] array) {
		this.array = array;

	public int constant() {
		return 2;

	public Implementer() {
You see that the class that implements this trait has an additional field, with a getter and a setter, and in its constructor it calls the static method of the trait(interface), which sets the field using the constant() method of the class, not the trait. If Implementer would not override the method, the default version returning 1 would be called.

You can have a look at the Java Bytecode if you download the scala file, compile it with scalac, and then use javap -c to dissassemble the resulting class files.
Does this answer your question?

Edit: I'm not allowed to append a scala file. So if you want to try yourself, copy the first code block in a scala file...



Zurück zu „Software Engineering - Design and Construction“