Scala Inheritance 2
Basics of Scala inheritance
As in Java or C++, you can declare a field or method as protected
. Such a member is accessible from any subclass, but not from other locations. Unlike in Java, a protected member is not visible throughout the package to which
the class belongs. (If you want this visibility, you can use a package modifier).
class Element{
protected def speak = println("Hi from element")
}
Recall that a class has one primary constructor and any number of auxiliary constructors, and that all auxiliary constructors must start with a call to a preceding auxiliary constructor or the primary constructor. As a consequence, an auxiliary constructor can never invoke a superclass constructor directly.
The auxiliary constructors of the subclass eventually call the primary constructor of the subclass. Only the primary constructor can call a superclass constructor. Recall that the primary constructor is intertwined with the class definition. The call to the superclass constructor is similarly intertwined. Here is an example
A field in Scala consists of a private field and
accessor/mutator methods. You can override a val
(or a parameterless def ) with
another val
field of the same name. The subclass has a private field and a public
getter, and the getter overrides the superclass getter (or method)
class Item(name: String){
override def toString = getClass.getName + " " + name
}
class Milk extends Item("Milk")
val milk = new Milk
println(milk.toString)
class Bullet extends Item("Bullet"){
override val name ="Flower"
}
- A
def
can only override anotherdef
. - A
val
can only override anotherval
or a parameterlessdef
. - A
var
can only override an abstractvar
- Cay Horstmann,
Scala for the Impatient 1st Edition