Inheritance is a fundamental concept in object-oriented programming that allows classes to inherit properties and behaviors from other classes. In Scala, inheritance provides a powerful mechanism for code reuse and creating hierarchical relationships between classes.
To create a subclass in Scala, use the extends
keyword followed by the name of the superclass. Here's a simple example:
class Animal {
def speak() = println("Animal makes a sound")
}
class Dog extends Animal {
override def speak() = println("Dog barks")
}
val myDog = new Dog()
myDog.speak() // Output: Dog barks
In this example, Dog
inherits from Animal
and overrides the speak()
method.
Scala supports abstract classes, which can contain both implemented and unimplemented methods. Subclasses must implement all abstract methods.
abstract class Shape {
def area(): Double
def perimeter(): Double
}
class Circle(radius: Double) extends Shape {
def area(): Double = Math.PI * radius * radius
def perimeter(): Double = 2 * Math.PI * radius
}
Traits in Scala are similar to interfaces in other languages but can also contain implemented methods. They provide a flexible way to share behavior among classes.
trait Flyable {
def fly(): Unit = println("Flying...")
}
class Bird extends Animal with Flyable
val sparrow = new Bird()
sparrow.fly() // Output: Flying...
Classes can extend multiple traits using the with
keyword.
When overriding methods in Scala, it's good practice to use the override
keyword. This helps prevent accidental overrides and makes the code more readable.
Inheritance in Scala provides a powerful tool for creating reusable and extensible code. By understanding and applying inheritance concepts, you can create more modular and maintainable Scala applications. Remember to use it wisely and consider alternatives like composition when appropriate.
For more advanced topics related to Scala's object-oriented features, explore Scala Classes and Scala Objects.