
- 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 - Superclass Construction
This chapter takes you through the concept of superclass construction in Scala programming. You can define a parent-child relationship between classes. So, a child class inherits the properties and methods of its parent class.
Superclass Construction
A class can extend another class, known as its superclass, to inherit its behavior. This relationship is established using the extends keyword. So, you can create constructor of the superclass from the subclass to initialize the inherited properties.
A subclass inherits fields and methods from its superclass. The subclass can also add new fields and methods. It can also override existing ones. When a subclass is instantiated, it must call the constructor of its superclass to initialize fields of the superclass.
Syntax
The syntax of the superclass construction is -
class Superclass { // fields and methods of the superclass } class Subclass extends Superclass { // fields and methods of the subclass }
Example
The following example shows superclass construction in Scala programing -
class Animal(name: String) { def eat(): Unit = { println(s"$name is eating") } } class Dog(name: String, breed: String) extends Animal(name) { def bark(): Unit = { println(s"$name is barking") } } object Demo { def main(args: Array[String]): Unit = { val dog = new Dog("Buddy", "Golden Retriever") dog.eat() // Buddy is eating dog.bark() // Buddy is barking } }
Save the above program in Demo.scala. Use the following commands to compile and execute this program.
Command
> scalac Demo.scala > scala Demo
Output
Buddy is eating Buddy is barking
In the example, the Animal class is defined as the superclass. This superclass has fields: a name and a method eat. The Dog class extends the Animal class. So it inherits its properties and methods. The Dog class also defines a new method bark. Demo object creates an instance of the Dog class and calls the inherited and new methods.
Calling Superclass Constructor
When a subclass is instantiated, the constructor of its superclass is called to initialize the inherited properties. You can call this explicit or implicit. It depends on whether the superclass constructor requires arguments.
Syntax
The syntax for calling superclass constructor -
class Superclass(param: Type) { // constructor body } class Subclass(param: Type, additionalParam: Type) extends Superclass(param) { // subclass constructor body }
Example
The following example shows calling a superclass constructor explicitly in Scala -
class Animal(name: String) { def eat(): Unit = { println(s"$name is eating") } } class Dog(name: String, breed: String) extends Animal(name) { def bark(): Unit = { println(s"$name is barking") } } object Demo { def main(args: Array[String]): Unit = { val dog = new Dog("Buddy", "Golden Retriever") dog.eat() // Buddy is eating dog.bark() // Buddy is barking } }
Save the above program in Demo.scala. Use the following commands to compile and execute this program.
Command
> scalac Demo.scala > scala Demo
Output
Buddy is eating Buddy is barking
In the example, the Dog class constructor explicitly calls Animal class constructor using extends Animal(name). So the name field is properly initialized in the Animal class before any other initialization in the Dog class.
Passing Parameters to Superclass Constructors
A subclass can pass parameters to the superclass constructor. So, you can inherit properties that are initialized correctly. It must pass arguments to the superclass constructor using extends SuperClassName(...).
Syntax
The syntax for passing parameters to superclass constructor -
class Superclass(param1: Type, param2: Type) { // constructor body } class Subclass(param1: Type, param2: Type, additionalParam: Type) extends Superclass(param1, param2) { // subclass constructor body }
Example
The following example shows passing parameters to the superclass constructor -
class Animal(name: String, age: Int) { def info(): Unit = { println(s"$name is $age years old") } } class Dog(name: String, age: Int, breed: String) extends Animal(name, age) { def bark(): Unit = { println(s"$name is barking") } } object Demo { def main(args: Array[String]): Unit = { val dog = new Dog("Buddy", 5, "Golden Retriever") dog.info() // Buddy is 5 years old dog.bark() // Buddy is barking } }
Save the above program in Demo.scala. Use the following commands to compile and execute this program.
Command
> scalac Demo.scala > scala Demo
Output
Buddy is 5 years old Buddy is barking
Overriding Superclass Methods
A subclass can override methods defined in its superclass to provide a specific implementation. The override keyword is used to override the method of superclass.
Syntax
The syntax to override method of superclass -
class Superclass { def methodName(): ReturnType = { // method body } } class Subclass extends Superclass { override def methodName(): ReturnType = { // overridden method body } }
Example
The following example shows overriding a method in the superclass -
class Animal(name: String) { def sound(): Unit = { println(s"$name makes a sound") } } class Dog(name: String, breed: String) extends Animal(name) { override def sound(): Unit = { println(s"$name barks") } } object Demo { def main(args: Array[String]): Unit = { val dog = new Dog("Buddy", "Golden Retriever") dog.sound() // Buddy barks } }
Save the above program in Demo.scala. Use the following commands to compile and execute this program.
Command
> scalac Demo.scala > scala Demo
Output
Buddy barks
In the example, the Dog class overrides the sound method defined in the Animal class. The override keyword. It is used to indicate that the sound method in the Dog class provides a specific implementation. The Demo object demonstrates how to call the overridden method.
Superclass Construction Summary
- You can define a parent-child relationship between classes. Child class inherits the properties and methods of its parent class.
- Subclass can call the constructor of its superclass to initialize inherited properties.
- Superclass constructor parameters can be passed for proper initialization of inherited fields.
- Subclasses can override methods defined in their superclasses. So it provide specific implementations using the override keyword.