Introduction to Scala Abstract Class
In Scala, abstract classes serve as blueprints for other classes. They can contain both abstract and concrete methods and can’t be instantiated themselves. This tutorial will guide you through the concepts and implementation of abstract classes in Scala, with practical code examples.
Key Concepts
- Definition of abstract classes
- Abstract methods vs. concrete methods
- Extending abstract classes
- Overriding methods in concrete classes
Creating an Abstract Class in Scala
To create an abstract class in Scala, you use the abstract
keyword. Abstract classes can contain abstract and non-abstract (concrete) methods.
abstract class Shape {
// Abstract method
def area(): Double
// Concrete method
def display(): Unit = println("Shape is being displayed.")
}
Extending an Abstract Class
To implement an abstract class, you need to extend it and provide implementations for all its abstract methods.
class Circle(radius: Double) extends Shape {
// Implementing abstract method
def area(): Double = math.Pi * radius * radius
}
Overriding Methods
In Scala, you can override both abstract and concrete methods from the abstract class.
class Square(side: Double) extends Shape {
// Implementing abstract method
def area(): Double = side * side
// Overriding concrete method
override def display(): Unit = println("Square is being displayed.")
}
Using Abstract Classes
You can use instances of concrete classes derived from abstract classes just like any other class instances.
val circle = new Circle(5)
println("Circle area: " + circle.area())
val square = new Square(4)
println("Square area: " + square.area())
square.display()
Conclusion
Abstract classes in Scala provide a powerful mechanism for defining common behavior across multiple classes while allowing for flexibility in implementation. By mastering abstract classes, you can write more concise and maintainable Scala code.