Home »
Scala
Abstract Classes in Scala
By IncludeHelp Last updated : October 26, 2024
In the Scala programming language, abstraction is achieved using abstract class.
Abstraction is the process of showing only functionality and hiding the details from the final user.
Abstract Classes
Abstract classes are defined using the "abstract" keyword. An abstract class contains both abstract and non-abstract methods. Multiple inheritances are not allowed by abstract class i.e. only one abstract class can be inherited by a class.
Syntax
Syntax to create abstract class in Scala:
abstract class class_name {
def abstract_method () {}
def method() {
//code
}
}
Abstract Method
An abstract method is that method which does not have any function body.
Syntax
The syntax for declaring an abstract method is as follows:
abstract class ClassName {
def abstractMethodName(param1: Type1, param2: Type2): ReturnType
}
Example of Abstract Classe
abstract class Bikes {
def displayDetails(): Unit
}
class MyBike extends Bikes {
def displayDetails(): Unit = {
println("My new bike name: Harley Davidson Iron 833")
println("Top speed: 192 km/h")
}
}
object MyObject {
def main(args: Array[String]): Unit = {
val newBike = new MyBike()
newBike.displayDetails()
}
}
Output
My new bike name : Harley Davidson Iron 833
Top speed : 192 kmph
Key Points on Abstract Classes
The following are key points regarding abstract classes in Scala:
- Instance creation of Abstract class is not allowed. If we try to create objects of abstract class then an error will be thrown.
- Field creation of an abstract class is allowed and can be used by methods of abstract class and classes that inherit it.
- A constructor can also be created in an abstract class which will be invoked by the instance of the inherited class.