Overview
In this article you will learn how to construct reusable parts of a program and deal with the tribulations of multiple inheritance.
A
A
A variable that is declared either by using
Scala Trait Example
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
trait Test{ def print() } class A extends Test{ def print(){ println("Hello") } } object MainObject{ def main(args:Array[String]){ var a = new A() a.print() } } |
Output
If a class extends a trait but does not implement the members declared in that trait, it must be declared abstract. Let’s see an example.
0 1 2 3 4 5 6 7 8 9 10 |
trait Test{ def print() } abstract class A extends Test{ // Must declared as abstract class def printA(){ println("Hello, this is A Class") } } |
Implementing Multiple Traits in a Class
If a class implements multiple traits, it will extend the first trait, class, abstract class. with keyword is used to extend rest of the traits.
You can achieve multiple inheritances by using trait.
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
trait Test{ def print() } trait Display{ def show() } class A6 extends Test with Display{ def print(){ println("This is Test Trait") } def show(){ println("This is Display Trait"); } } object MainObject{ def main(args:Array[String]){ var a = new A6() a.print() a.show() } } |
Output
Scala Trait having abstract and non-abstract methods
You can also define method in trait as like in abstract class. I.e. you can treat trait as abstract class also. In scala, trait is almost same as abstract class except that it can’t have constructor. You can’t extend multiple abstract classes but can extend multiple traits.
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
trait Test{ def print() // Abstract method def show(){ // Non-abstract method println("This is show method") } } class A extends Test{ def print(){ println("This is print method") } } object MainObject{ def main(args:Array[String]){ var a = new A() a.print() a.show() } } |
Output
This is all about trait in Scala.Hope you like it.Keep Learning and Sharing!! :)