Abstract classes

An abstract class in Scala can have constructor parameters as well as type parameters. An abstract class in Scala is fully interoperable with Java. In other words, it is possible to call them from Java code without any intermediate wrappers.

So, what is the difference between an abstract class and the traits in Scala? As you have seen, an abstract class can have constructor parameters, type parameters, and multiple parameters. However, a trait in Scala can have only type parameters. The following is a simple example of an abstract class:

abstract class Animal(animalName:String = "notset") {
//Method with definition/return type
def getAnimalAge
//Method with no definition with String return type
def getAnimalGender : String
//Explicit way of saying that no implementation is present
def getAnimalOrigin () : String {}
//Method with its functionality implemented
//Need not be implemented by subclasses, can be overridden if required
def getAnimalName : String = {
animalName
}
}

In order to extend this class by another one, we need to implement the unimplemented methods earlier getAnimalAge, getAnimalGender, and getAnimalOrigin. For getAnimalName, we can override it or not, since its implementation is already there.

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

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