Abstract classes and the override keyword

If you want to override a concrete method from the superclass, the override modifier is necessary. However, if you are implementing an abstract method, it is not strictly necessary to add the override modifier. Scala uses the override keyword to override a method from a parent class. For example, suppose you have the following abstract class and a method printContents() to print your message on the console:

abstract class MyWriter {
var message: String = "null"
def setMessage(message: String):Unit
def printMessage():Unit
}

Now, add a concrete implementation of the preceding abstract class to print the contents on the console as follows:

class ConsolePrinter extends MyWriter {
def setMessage(contents: String):Unit= {
this.message = contents
}

def printMessage():Unit= {
println(message)
}
}

Secondly, if you want to create a trait to modify the behavior of the preceding concrete class, as follows:

trait lowerCase extends MyWriter {
abstract override def setMessage(contents: String) = printMessage()
}

If you look at the preceding code segment carefully, you will find two modifiers (that is, abstract and override). Now, with the preceding setting, you can do the following to use the preceding class:

val printer:ConsolePrinter = new ConsolePrinter()
printer.setMessage("Hello! world!")
printer.printMessage()

In summary, we can add an override keyword in front of the method to work as expected.

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

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