Inheritance and Polymorphism
Explore object-oriented principles like inheritance, abstract classes, and polymorphism in Scala.
What is Inheritance?
Inheritance is a fundamental concept in Object-Oriented Programming (OOP) that allows a new class to inherit properties and behaviors (methods) from an existing class.
Think of it as a 'parent-child' relationship. The 'child' class (subclass) reuses code from the 'parent' class (superclass), saving time and ensuring consistency.
- Promotes code reuse.
- Establishes an 'is-a' relationship (e.g., a Dog is an Animal).
- Helps organize code into a hierarchy.
Your First Base Class
Let's define a simple Animal class. This will be our base class, also known as a superclass or parent class. It has a basic behavior: to speak.
Run the code to see our generic animal in action!
class Animal {
val name: String = "Generic Animal"
def speak(): Unit = {
println(s"$name makes a sound.")
}
}
object Main {
def main(args: Array[String]): Unit = {
val myAnimal = new Animal()
myAnimal.speak()
}
}All lessons in this course
- Classes, Objects, and Packaging
- Inheritance and Polymorphism