Extending a Class

Extending a base class in Scala is similar to extending in Java except for two good restrictions: method overriding requires the override keyword, and only the primary constructor can pass parameters to a base constructor.

The Override annotation was introduced in Java 5 but its use is optional in Java. Scala insists that the keyword override is used when overriding a method. By requiring that keyword, Scala will help minimize errors that often arise from typos in method names. You can avoid either accidentally overriding a method unintentionally or writing a new method when your intent was to override a base method.

In Scala, auxiliary constructors have to call either the primary constructor or another auxiliary constructor. In addition, you can pass parameters to a base constructor only from the primary constructor. At first this may appear to be an unnecessary restriction, but Scala imposes this rule for a good reason—it reduces errors that often creep in due to duplication of logic among constructors of a class.

In essence, the primary constructor acts as the gateway to initialize an instance of a class, and the interaction with the base class for initialization is controlled through this.

As an example, let’s extend a class:

WorkingWithObjects/Vehicle.scala
 
class​ Vehicle(​val​ id: ​Int​, ​val​ year: ​Int​) {
 
override​ ​def​ toString = s​"ID: $id Year: $year"
 
}
 
 
class​ Car(​override​ ​val​ id: ​Int​, ​override​ ​val​ year: ​Int​, ​var​ fuelLevel: ​Int​)
 
extends​ Vehicle(id, year) {
 
override​ ​def​ toString = s​"${super.toString} Fuel Level: $fuelLevel"
 
}
 
 
val​ car = ​new​ Car(1, 2015, 100)
 
println(car)

Take a look at the output of running this code:

 
ID: 1 Year: 2015 Fuel Level: 100

Since the properties id and year in Car are derived from Vehicle, we indicate that in the Car class by using the keyword override before the respective parameters of the primary constructor. Seeing this keyword, the Scala compiler will not generate fields for these two properties. Instead, it will route the accessor methods for these properties to the appropriate methods of the base class. If you forget to put in the override keyword for these two parameters, you’ll get a compiler error.

Also, since we’re overriding the toString method of java.lang.Object in Vehicle and in Car, we had to prefix the definitions of toString with override as well.

When extending a class you must pass the parameters from the derived class to one of the base class constructors. Since only the primary constructor can invoke a base constructor, place this call right after the base class name is mentioned, following the extends declaration.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.64.66