Traits and inheritance

It's possible to do inheritance in Scala as well. For such a task, you use the operator extend after the class definition. Scala just allows you to extend one class, just like Java. Java does not allow multiple inheritance like C++. However, Scala allows it by using the Mixing technique with traits. Scala traits are like Java interface, but you can also add concrete code, and you are allowed to have as many traits as you want in your code.

Scala inheritance code in Scala REPL

Following is a Scala inheritance code in Scala REPL:

$ scala

Welcome to Scala 2.11.8 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_77). Type in expressions for evaluation. Or try :help. scala>class Person(

| @scala.beans.BeanProperty var name:String = "",

| @scala.beans.BeanProperty var age:Int = 0 | ){

| name = name.toUpperCase

| override def toString = "name: " + name + " age: " + age | }

defined class Person scala>

scala>class LowerCasePerson(name:String,age:Int) extends Person(name,age)


| setName(name.toLowerCase)

| }

defined class LowerCasePerson scala>

scala>val p = new LowerCasePerson("DIEGO PACHECO",31)

p: LowerCasePerson = name: diego pacheco age: 31


res0: String = diego pacheco


Scala does not make constructors inheritance like Java. So you need to rewrite the constructors and pass the values through a super class. All code inside the class will be the secondary constructor. All code inside parentheses () in the class definition will be the primary constructor. It's possible to have multiple constructors using the this operator. For this particular implementation, we changed the default behavior and added new constructor code in order to make the given name lower case, instead of the default uppercase defined by the Person superclass.

< Prev   CONTENTS   Source   Next >