Scala inheritance 2

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")
    
}
defined class 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

Overriding fields

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
}
defined class Item
class Milk extends Item("Milk")
defined class Milk
val milk = new Milk
println(milk.toString)
ammonite.$sess.cmd2$Helper$Milk Milk
milk: Milk = ammonite.$sess.cmd2$Helper$Milk Milk
class Bullet extends Item("Bullet"){
    override val name ="Flower"
}
cmd4.sc:2: value name overrides nothing
    override val name ="Flower"
                 ^Compilation Failed
Compilation Failed
  • A def can only override another def .
  • A val can only override another val or a parameterless def .
  • A var can only override an abstract var

Anonymous subclasses

References

  1. Cay Horstmann, Scala for the Impatient 1st Edition