Open In App

Calling A Super Class Constructor in Scala

Prerequisite – Scala Constructors
In Scala, Constructors are used to initialize an object’s state and are executed at the time of object creation. There is a single primary constructor and all the other constructors must ultimately chain into it. When we define a subclass in Scala, we control the superclass constructor that is called by its primary constructor when we define the extends portion of the subclass declaration. 
 




// Scala program to illustrate
// calling a super class constructor
 
// Primary constructor
class GFG (var message: String)
{
    println(message)
}
 
 
// Calling the super class constructor
class Subclass (message: String) extends GFG (message)
{
    def display()
    {
        println("Subclass constructor called")
    }
}
 
// Creating object
object Main
{
    // Main method
    def main(args: Array[String])
    {
         
        // Creating object of Subclass
        var obj = new Subclass("Geeksforgeeks");
        obj.display();
    }
}

Output: 

Geeksforgeeks
Subclass constructor called

 




// Scala program to illustrate
// calling a specific super class constructor
 
// Primary constructor (1)
class GFG (var message: String, var num: Int)
{
     
    println(message+num)
     
    // Auxiliary constructor (2)
    def this (message: String)
    {
        this(message, 0)
         
    }
     
}
 
// Calling the super class constructor with 2 arguments
class Subclass (message: String) extends GFG (message, 3000)
{
    def display()
    {
        println("Subclass constructor called")
    }
}
 
// Creating object
object GFG
{
    // Main method
    def main(args: Array[String])
    {
         
        // Creating object of Subclass
        var obj = new Subclass("Article count ");
        obj.display();
    }
}

Output: 
Article count 3000
Subclass constructor called

 




// Scala program to illustrate
// calling a specific super class constructor
 
// Primary constructor (1)
class GFG (var message: String, var num: Int)
{
     
    println(message + num)
     
    // Auxiliary constructor (2)
    def this (message: String)
    {
        this(message, 0)
         
    }
     
}
 
 
// Calling the superclass constructor with 1 arguments
class Subclass (message: String) extends GFG (message)
{
    def display()
    {
        println("Subclass constructor called")
    }
}
 
// Creating object
object GFG
{
    // Main method
    def main(args: Array[String])
    {
         
        // Creating object of Subclass
        var obj = new Subclass("Article Count ");
        obj.display();
    }
}

Output: 

Article Count 0
Subclass constructor called

 

 


Article Tags :