Abstract classes and traits are powerful features in Scala that allow you to define behavior and share it across multiple classes. Here's a brief overview of abstract classes and traits in Scala: 1. Abstract classes: An abstract class in Scala is a class that cannot be instantiated and can only be used as a base class for other classes. Abstract classes can contain abstract and non-abstract methods. An abstract method is a method without a body that must be implemented by any concrete class that extends the abstract class. Here's an example:
abstract class Animal {
def makeSound(): Unit
def walk(): Unit = {
println(“The animal is walking”)
}
}
class Dog extends Animal {
override def makeSound(): Unit = {
println(“The dog barks”)
}
}
val animal: Animal = new Dog()
animal.makeSound() // prints “The dog barks”
animal.walk() // prints “The animal is walking”
`
In this example, “Animal” is an abstract class that defines an abstract method “makeSound” and a non-abstract method “walk”. “Dog” is a concrete class that extends “Animal” and provides an implementation of the “makeSound” method. We create an instance of “Dog” and assign it to a variable of type “Animal”, which allows us to call both the “makeSound” and “walk” methods.
2. Traits:A trait in Scala is similar to an interface in other object-oriented languages. A trait can define methods and fields, but it cannot have a constructor. Traits can be mixed in with classes to provide additional behavior. Here’s an example:
“
trait Greeting {
def sayHello(name: String): Unit = {
println(s”Hello, $name!”)
}
}
class Person(name: String) extends Greeting {
def introduce(): Unit = {
println(s”My name is $name”)
}
}
val person = new Person(“John”)
person.introduce() // prints “My name is John”
person.sayHello(“Mary”) // prints “Hello, Mary!”
“
In this example, “Greeting” is a trait that defines a method “sayHello”. “Person” is a class that extends “Greeting” and provides its own method “introduce”. We create an instance of “Person” and call both the “introduce” and “sayHello” methods.
Overall, abstract classes and traits in Scala provide a powerful way to define behavior and share it across multiple classes. Abstract classes can define both abstract and non-abstract methods, while traits can be mixed in with classes to provide additional behavior. Both abstract classes and traits are important features of Scala’s object-oriented programming model.