Abstract classes
We can define abstract classes using the abstract
keyword:
abstract class Person class Customer extends Person class Employee extends Person
Here, what we wanted was two subclasses that can also be treated as instances of a superclass, in our case, Person
. For now, we have not shown any behavior in our abstract class. But, there are times when we want to imply some behaviors in our abstract classes that subsequent subclasses can inherit and define for themselves:
abstract class Person(category: String) { val idPrefix: String } class Customer extends Person("External") { override val idPrefix: String = "CUST" } class Employee extends Person("Internal") { override val idPrefix: String = "EMP" }
Our intention to use abstract classes is clearer now. We may want a set of classes that inherit methods or values from a particular class. When we extend classes, we can use the override
modifier in our definition. This kind of behavior is likely to present itself...