Comparing and contrasting: val and final

Just like Java, the final keyword also exists in Scala, which works somehow similar to the val keyword. In order to differentiate between the val and final keywords in Scala, let's declare a simple animal class, as follows:

class Animal {
val age = 2
}

As mentioned in Chapter 1, Introduction to Scala, while listing Scala features, Scala can override variables which don't exist in Java:

class Cat extends Animal{
override val age = 3
def printAge ={
println(age)
}
}

Now, before going deeper, a quick discussion on the keyword extends is a mandate. Refer to the following information box for details.

Using Scala, classes can be extensible. A subclass mechanism using the extends keyword makes it possible to specialize a class by inheriting all members of a given superclass and defining additional class members. Let's look at an example, as follows:
class Coordinate(xc: Int, yc: Int) {
val x: Int = xc
val y: Int = yc
def move(dx: Int, dy: Int): Coordinate = new Coordinate(x + dx, y + dy)
}
class ColorCoordinate(u: Int, v: Int, c: String) extends Coordinate(u, v) {
val color: String = c
def compareWith(pt: ColorCoordinate): Boolean = (pt.x == x) && (pt.y == y) && (pt.color == color)
override def move(dx: Int, dy: Int): ColorCoordinate = new ColorCoordinate(x + dy, y + dy, color)
}

However, if we declared the age variable as final in the Animal class, then the Cat class will not be able to override it, and it will give the following error. For this Animal example, you should have learned when to use the final keyword. Let's see an example of this:

scala> class Animal {
| final val age = 3
| }
defined class Animal
scala> class Cat extends Animal {
| override val age = 5
| }
<console>:13: error: overriding value age in class Animal of type Int(3)
value age cannot override final member
override val age = 5
^
scala>

Well done! To achieve the best encapsulation - also called information hiding - you should always declare methods with the least visibility that works. In the next subsection, we will learn how the access and visibility of classes, companion objects, packages, subclasses, and projects work.

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

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