In Scala, an abstract class is a class that cannot be instantiated directly but serves as a blueprint for other classes. Abstract classes can contain both abstract and non-abstract (concrete) members, including fields and methods. Abstract members declared within an abstract class are meant to be implemented by concrete subclasses. Here's how you define and use abstract classes in Scala:
Defining an Abstract Class:
You define an abstract class using the abstract keyword. Abstract classes can have fields, methods, and constructors, just like regular classes. However, they may also contain abstract members, which are declared without an implementation:
abstract class Animal {
val name: String
def speak(): Unit
}
In this example, Animal is an abstract class with an abstract field name and an abstract method speak(). Subclasses must provide concrete implementations for these members.
Extending an Abstract Class:
To create a concrete subclass of an abstract class, you use the extends keyword:
class Dog(val name: String) extends Animal {
def speak(): Unit = {
println(s"$name says Woof!")
}
}
Here, the Dog class extends the Animal abstract class and provides concrete implementations for both the name field and the speak() method.
Creating Instances:
You can create instances of concrete subclasses, but not of the abstract class itself:
val myDog = new Dog("Buddy")
myDog.speak() // Output: Buddy says Woof!
Attempting to create an instance of the abstract class directly (val myAnimal = new Animal) will result in a compilation error because abstract classes cannot be instantiated.
Abstract Class Inheritance:
Abstract classes can also inherit from other classes, whether they are abstract or concrete. Subclasses of abstract classes must provide concrete implementations for all abstract members inherited from their superclasses.
abstract class Mammal extends Animal {
def giveBirth(): Unit
}
A concrete subclass of Mammal must provide implementations for both speak() and giveBirth().
In summary, abstract classes in Scala provide a way to define common behaviors and structures that can be shared among multiple subclasses. They allow you to create a contract that concrete subclasses must adhere to by providing implementations for abstract members. Abstract classes are a fundamental part of Scala's support for object-oriented programming and code organization.