
- Scala - Home
- Scala - Overview
- Scala - Features
- Scala - Environment Setup
- Scala - Build Tool (SBT)
- Scala - REPL
- Scala - Dot & Dotty
- Scala - Basic Syntax
- Scala - Hello World Program
- Scala - Identifiers
- Scala - Keywords
- Scala - Comments
- Scala - Code Blocks
- Scala - Semicolon
- Scala - Constructs
- Scala - Expressions
- Scala - Input and Output
- Scala - Optional Braces
- Scala - Underscore (_)
- Data Types and Variables
- Scala - Data Types
- Scala - Type Bounds
- Scala - Context Bound
- Scala - Variances
- Scala - Type Hierarchy
- Scala - Variables
- Scala - Variable Scopes
- Scala - Literals
- Scala - Numeric Types
- Scala - Boolean Types
- Scala - Char Type
- Scala - Unit Types
- Scala - Strings
- Scala - Arrays
- Scala - Null Type
- Scala - Nothing
- Scala - Any Type
- Scala - AnyRef Type
- Scala - Unified Types
- Scala - Dates and Times
- Scala - Ranges
- Scala - Multidimensional Arrays
- Scala - WrappedArray
- Scala - StringBuilder
- Scala - String Interpolation
- Scala - StringContext
- Scala - Type Casting
- Scala var vs val
- Scala Operators
- Scala - Operators
- Scala - Rules for Operators
- Scala - Arithmetic Operators
- Scala - Relational Operators
- Scala - Logical Operators
- Scala - Bitwise Operators
- Scala - Assignment Operators
- Scala - Operators Precedence
- Scala - Symbolic Operators
- Scala - Range Operator
- Scala - String Concatenation Operator
- Scala Conditional Statements
- Scala - IF ELSE
- Scala - IF-ELSE-IF-ELSE Statement
- Scala - Nested IF-ELSE Statement
- Scala Loop Statements
- Scala - Loop Statements
- Scala - while Loop
- Scala - do-while Loop
- Scala - Nested Loops
- Scala - for Loop
- Scala - break Statement
- Scala - yield Keyword
- Scala Classes & Objects
- Scala - Classes & Objects
- Scala - Constructors
- Scala - Auxiliary Constructor
- Scala - Primary Constructor
- Scala - This Keyword
- Scala - Nested Classes
- Scala - Getters and Setters
- Scala - Object Private Fields
- Scala - Singleton Object
- Scala - Companion Objects
- Scala - Creating Executable Programs
- Scala - Stateful Object
- Scala - Enumerations
- Scala - Polymorphism
- Scala - Access Modifiers
- Scala - Apply Method
- Scala - Update Methods
- Scala - UnapplySeq Method
- Scala - Inheritance
- Scala - Extending a Class
- Scala - Method Overloading
- Scala - Method Overriding
- Scala - Generic Classes
- Scala - Generic Functions
- Scala - Superclass Construction
- Scala Methods & Functions
- Scala - Functions
- Scala - Main Methods
- Scala - Functions Call-by-Name
- Scala - Functions with Named Arguments
- Scala - Function with Variable Arguments
- Scala - Recursion Functions
- Scala - Default Parameter Values
- Scala - Functions without Parameters
- Scala - Implicit Parameters
- Scala - Higher-Order Functions
- Scala - Nested Functions
- Scala - Extension Methods
- Scala - Anonymous Functions
- Partially Applied Functions
- Scala - Lazy Val
- Scala - Pure Function
- Scala - Currying Functions
- Scala - Control Abstractions
- Scala - Corecursion
- Scala - Unfold
- Scala - Tail Recursion
- Scala - Infinite Sequences
- Scala - Dynamic Invocation
- Scala - Lambda Expressions
- Scala Collections
- Scala - Collections
- Mutable and Immutable Collections
- Scala - Lists
- Scala - Sets
- Scala - Maps
- Scala - TreeMap
- Scala - SortedMap
- Scala - Tuples
- Scala - Iterators
- Scala - Options
- Scala - Infinite Streams
- Scala - Parallel Collections
- Scala - Algebraic Data Types
- Scala Pattern Matching
- Scala - Pattern Matching
- Scala - Type Patterns
- Scala - Exception Handling
- Scala - Extractors
- Scala - Regular Expressions
- Scala Files I/O
- Scala - Files I/O
- Scala Advanced Concepts
- Scala - Closures
- Scala - Futures
- Scala - Promises
- Scala - Traits
- Scala - Trait Mixins
- Scala - Layered Traits
- Scala - Trait Linearization
- Scala - Sealed Traits
- Scala - Transparent Traits
- Scala - Literal Type Arithmetic
- Scala - Inline keyword
- Scala - Def, Var & Val
- Scala - Dropped Features
- Scala - BDD Testing
Scala - Inheritance
We will discuss inheritance in Scala programming in this chapter. You can inherit properties and methods from another class. So, the code can be reused and the creation of hierarchical class structures.
Inheritance
Inheritance is a fundamental concept in object-oriented programming. You can inherit new class (subclass) fields and methods from an existing class (superclass). The class that is inherited from is called the superclass. The class that inherits is called the subclass. The subclass can also override inherited methods and define new methods and fields.
One class can acquire the properties (fields) and methods of another class. So, there will be code reuse and code reuse and the creation of hierarchical relationships between classes.
Syntax
The syntax of the inheritance in Scala is -
class Superclass { // superclass definition } class Subclass extends Superclass { // subclass definition }
Example
The following example shows basic inheritance in Scala programming -
class Animal { def eat(): Unit = { println("Animal is eating") } } class Dog extends Animal { def bark(): Unit = { println("Dog is barking") } } object Demo { def main(args: Array[String]): Unit = { val dog = new Dog() dog.eat() // Inherited method dog.bark() // Subclass method } }
Save the above program in Demo.scala. Use the following commands to compile and execute this program.
Command
> scalac Demo.scala > scala Demo
Output
Animal is eating Dog is barking
In the example, the Dog class extends the Animal class. It inherited its eat method. Dog class also defines its own method, bark. Demo object creates instance of Dog and calls both inherited and subclass methods.
Method Overriding
Subclass can override a method defined in its superclass. The override keyword is used to indicate that a method is being overridden.
Syntax
The syntax of overriding in Scala is -
class Superclass { def method(): Unit = { // superclass method } } class Subclass extends Superclass { override def method(): Unit = { // subclass method } }
Example
The following example shows method overriding in Scala programming -
class Animal { def sound(): Unit = { println("Animal sound") } } class Dog extends Animal { override def sound(): Unit = { println("Dog Bark") } } object Demo { def main(args: Array[String]): Unit = { val animal: Animal = new Dog() animal.sound() // Calls the overridden method in Dog } }
Save the above program in Demo.scala. Use the following commands to compile and execute this program.
Command
> scalac Demo.scala > scala Demo
Output
Dog Bark
In the example, Dog class overrides the sound method of the Animal class. Demo object shows polymorphism by using a reference of type Animal. It calls the overridden method in the Dog class.
Inheritance Using the super Keyword
The super keyword in Scala is used to call a method or constructor defined in the superclass from within a subclass.
Syntax
The syntax of super keyword to call method in subclass is -
class Superclass { def method(): Unit = { // superclass method } } class Subclass extends Superclass { override def method(): Unit = { super.method() // calls superclass method // additional subclass logic } }
Example
The following example shows using the super keyword in Scala programming -
class Animal { def sound(): Unit = { println("Animal sound") } } class Dog extends Animal { override def sound(): Unit = { super.sound() println("Dog barks") } } object Demo { def main(args: Array[String]): Unit = { val dog = new Dog dog.sound() } }
Save the above program in Demo.scala. Use the following commands to compile and execute this program.
Command
> scalac Demo.scala > scala Demo
Output
Animal sound Dog barks
In the example, Dog class uses the super keyword to call the sound method of the Animal class. It calls before adding its own implementation. The Demo object creates an instance of the Dog class and calls the overridden sound method.
Constructor Inheritance
Constructors are not inherited. Instead, subclass can call superclass constructor using the extends keyword.
Syntax
The syntax of the constructor inheritance is -
class Superclass(val param: Type) { // superclass definition } class Subclass(param: Type) extends Superclass(param) { // subclass definition }
Example
The following example shows constructor inheritance in Scala -
class Animal(val name: String) { def display(): Unit = { println(s"Animal: $name") } } class Dog(name: String, val breed: String) extends Animal(name) { def displayBreed(): Unit = { println(s"Breed: $breed") } } object Demo { def main(args: Array[String]): Unit = { val dog = new Dog("Buddy", "Golden Retriever") dog.display() // Calls Animal's display method dog.displayBreed() // Calls Dog's displayBreed method } }
Save the above program in Demo.scala. Use the following commands to compile and execute this program.
Command
> scalac Demo.scala > scala Demo
Output
Animal: Buddy Breed: Golden Retriever
In the example, Dog class extends Animal class. It calls Animal constructor using the extends keyword. Demo object creates instance of Dog and calls both the inherited display method and the subclass's displayBreed method.
Abstract Classes
An abstract class in Scala cannot be instantiated. It has abstract methods (methods without implementation) as well as concrete methods (methods with implementation). Subclasses must provide implementations for the abstract methods.
Syntax
The syntax of the abstract classes is -
abstract class Superclass { def abstractMethod(): Unit // abstract method } class Subclass extends Superclass { def abstractMethod(): Unit = { // method implementation } }
Example
The following example shows abstract classes and methods in Scala.
abstract class Animal { def sound(): Unit } class Dog extends Animal { def sound(): Unit = { println("Dog barks") } } object Demo { def main(args: Array[String]): Unit = { val dog = new Dog dog.sound() } }
Save the above program in Demo.scala. Use the following commands to compile and execute this program.
Command
> scalac Demo.scala > scala Demo
Output
Dog barks
In the example, Animal class is abstract class. It defines an abstract method sound. Dog class extends the Animal class and provides an implementation for the sound method. The Demo object creates an instance of the Dog class and calls the implemented sound method.
Traits
Traits in Scala are similar to interfaces in Java. Traits can have abstract methods and concrete methods. A class can extend multiple traits. So you can implement multiple inheritance.
Syntax
The syntax of the traits is -
trait TraitName { def abstractMethod(): ReturnType def concreteMethod(): ReturnType = { // Implementation } } class ClassName extends TraitName { // Implementation of abstract methods }
Example
The following example shows the use of traits in Scala programming -
trait Animal { def sound(): Unit } trait Pet { def play(): Unit = { println("Pet is playing") } } class Dog extends Animal with Pet { def sound(): Unit = { println("Dog barks") } } object Demo { def main(args: Array[String]): Unit = { val dog = new Dog dog.sound() dog.play() } }
Save the above program in Demo.scala. Use the following commands to compile and execute this program.
Command
> scalac Demo.scala > scala Demo
Output
Dog barks Pet is playing
In the example, Dog class extends both the Animal trait and the Pet trait. Demo object creates an instance of the Dog class and calls methods from both traits.
Inheritance Summary
- You can inherit new class (subclass) fields and methods from an existing class (superclass). So, there can be code reusability.
- A subclass can override methods from its superclass using the override keyword.
- The super keyword is used to call methods and constructors from the superclass.
- Abstract classes in Scala can have abstract and concrete methods and cannot be instantiated.
- You can implement multiple inheritance in Scala using Traits. So a class can extend multiple traits.