I have been looking at examples online, and tutorials, and I cannot find anything that explains how this (inheritance) differs from java. Simple example:
class Shape {
String type;
Shape(String type) {
this.type = type;
}
...
}
class Square extends Shape {
Square(String name){
Super(name);
}
....
}
Whats confusing me is in the above example I need to call the super class in order to set the ‘type’ variable, as well as to access it to tell me the Box objects’ type as well. In Scala, how can this be done? I know scala uses traits interfaces as well, but is the above example omitted completely from scala? Can anyone direct me to a good example or explain it. I really appreciate it.
You can write almost exactly the same thing in Scala, much more concisely:
In the first line, the fact that
typeis preceded byvarmakes the compiler add getters and setters (from “5.3 Class Definitions” in the specification):In the second line
nameis not preceded byvalorvar, and is therefore just a constructor parameter, which is this case we pass on to the superclass constructor in theextendsclause. No getters or setters are added forname, so if we created an instancesquareofSquareand calledsquare.name, it wouldn’t compile.Note also that
typeis a keyword in Scala, so I’ve had to surround it by backticks in both the definition and the example above:There are many, many resource that you can read for more information about inheritance in Scala. See for example Chapters 4 and 5 of Programming Scala.