Category : Scala | Sub Category : Scala Programs | By Prasad Bonam Last updated: 2023-10-21 03:27:41 Viewed : 564
In Scala, inheritance and polymorphism work similarly to other object-oriented programming languages, allowing classes to inherit fields and methods from other classes and enabling the use of polymorphic behavior through method overriding. Here is an overview of inheritance and polymorphism in Scala:
Inheritance:
extends
keyword is used to declare that one class extends another.scalaclass Animal(val name: String) { def sound(): String = "Some sound" } class Dog(name: String) extends Animal(name) { override def sound(): String = "Woof" }
Polymorphism:
override
keyword is used to indicate that a method is being overridden.scalaval animal: Animal = new Dog("Buddy") println(animal.sound()) // Output: "Woof"
In these examples, the first one demonstrates inheritance with the Animal
and Dog
classes, where the Dog
class extends the Animal
class and overrides the sound
method. The second example illustrates polymorphism, where an instance of the Dog
class is assigned to a variable of type Animal
, demonstrating that a subclass instance can be treated as an instance of its superclass.
inheritance and polymorphism with examples and corresponding outputs in Scala.
Example of Inheritance:
scalaclass Animal(val name: String) { def sound(): String = "Some sound" } class Dog(name: String) extends Animal(name) { override def sound(): String = "Woof" } // Creating instances of Animal and Dog val animal = new Animal("Generic Animal") val dog = new Dog("Buddy") // Calling the sound method for both instances println(animal.sound()) // Output: "Some sound" println(dog.sound()) // Output: "Woof"
In this example, we have an Animal
class with a method sound
and a Dog
class that extends the Animal
class. The sound
method is overridden in the Dog
class to return "Woof". When we create instances of Animal
and Dog
and call the sound
method, we get the respective outputs.
Example of Polymorphism:
scalaclass Animal(val name: String) { def sound(): String = "Some sound" } class Dog(name: String) extends Animal(name) { override def sound(): String = "Woof" } // Polymorphism example val animal: Animal = new Dog("Buddy") println(animal.sound()) // Output: "Woof"
In this example, we have an Animal
class and a Dog
class that extends the Animal
class. We create an instance of Dog
and assign it to a variable of type Animal
. Even though the variable is of type Animal
, it holds an instance of Dog
. When we call the sound
method using the animal
variable, it invokes the overridden method from the Dog
class, demonstrating polymorphic behavior.
These examples illustrate how inheritance and polymorphism work in Scala, showcasing the relationship between superclass and subclass, and the ability to treat objects of different types as instances of a common superclass.