4.13. Defining Properties in an Abstract Base Class (or Trait)
Problem
You want to define abstract or concrete properties in an abstract base class (or trait) that can be referenced in all child classes.
Solution
You can declare both val and
var fields in an abstract class (or
trait), and those fields can be abstract or have concrete
implementations. All of these variations are shown in this
recipe.
Abstract val and var fields
The following example demonstrates an Animal trait with abstract val and var fields, along with a simple concrete
method named sayHello, and an
override of the toString
method:
abstractclassPet(name:String){valgreeting:Stringvarage:IntdefsayHello{println(greeting)}overridedeftoString=s"I say $greeting, and I'm $age"}
The following Dog and
Cat classes extend the Animal class and provide values for the
greeting and age fields. Notice that the fields are again
specified as val or var:
classDog(name:String)extendsPet(name){valgreeting="Woof"varage=2}classCat(name:String)extendsPet(name){valgreeting="Meow"varage=5}
The functionality can be demonstrated with a simple driver object:
objectAbstractFieldsDemoextendsApp{valdog=newDog("Fido")valcat=newCat("Morris")dog.sayHellocat.sayHelloprintln(dog)println(cat)// verify that the age can be changedcat.age=10println(cat)}
The resulting output looks like this:
Woof Meow I say Woof, and I'm 2 I say Meow, and I'm 5 I say Meow, and I'm 10
Concrete field implementations ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access