Hello,
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?
Thanks
Template Method Pattern slide HashTable
Moderatoren: pmueller, SE - Design and Construction
Re: Template Method Pattern slide HashTable
Hi,
no HashTable does not have a real superclass constructor since it is a trait.
Here is small example to illustrate this:
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:
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...
Best,
Patrick
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
}
Code: Alles auswählen
interface Test {
public static int constant$(Test test) {
test.constant();
}
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) {
test.array_$eq(test.constant())
}
}
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() {
super();
Test.$init$(this);
}
}
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...
Best,
Patrick