Inheritance and Traits3:17 with andi mitre
In this video, we’ll define what traits are in Scala and how to use them. We will create our own traits and show how to inherit multiple traits.
Traits -- In Scala, auxiliary constructors refer to secondary or additional constructors which accept different parameters from the primary constructor. They are defined using ‘def this()’ and always call either the primary constructor or another previously defined auxiliary constructor.
Similar to Java, 0:00 Scala can inherit from another class by using the extends keyword. 0:01 Let's take a look at how to extend a class and 0:06 override methods in fields, in a subclass. 0:08 Let's get back in to our project and create a new Villain class. 0:12 Great, we've created a Villain class which inherits from the SuperHero class. 1:04 We can call the details method over subclass 1:09 which overrides the details function of the super class. 1:11 Our function should print out the name and the string is a notorious villain. 1:15 To recap, we've created a class Villain which extends SuperHero 1:20 by calling the primary constructor in the SuperHero class. 1:23 Additionally, we have overrated the details method 1:27 to print a different statement if the object is of type Villain. 1:30 Let's create a villain and see our results. 1:34 Great. 1:51 Let's see our results. 1:52 Awesome, a new villain was created, and 1:55 loki.details prints out that Loki is a notorious villain. 1:58 Additionally, we can access all the properties of our Super class, and 2:02 we've set Loki's age to 26. 2:07 Let's understand what is going on under the hood. 2:09 When we create a new instance of a villain, the villain constructor is 2:12 invoked, which ultimately invokes the constructor of the Super class, SuperHero. 2:15 Therefore, creating a new villain. 2:20 Another thing to point out is that the protected fields or methods in Scala 2:23 are only accessible within subclasses, which is quite different from Java 2:27 where protected fields and methods are visible throughout the package. 2:32 Similarly to Java, a final field or method cannot be overwritten, 2:36 you can also declare a class as final so it cannot be extended. 2:40 Let’s change the details function in our SuperHero class to a final method. 2:45 By doing so, if we switch back to our Villain class, we’ll notice that 2:51 the details method is underlined in red, therefore, we cannot override it here. 2:56 And if we rerun our app, we'll be able to see that same exact error. 3:02 In the next video, 3:07 we will start discussing traits, another great feature that Scala provides. 3:08 Traits allow us to mix in other functionality within our class. 3:12
You need to sign up for Treehouse in order to download course files.Sign up