Auxiliary Constructor

What is Auxiliary Constructor ?

 
In Scala, a class can have a primary constructor and zero or more auxiliary constructors, also called secondary constructors.

The primary constructor is the entire body of the class.

We can define one or more auxiliary constructors for a class to provide different ways to create objects.
 

Defining Auxiliary Constructor

 
Auxiliary constructors are defined by creating methods named this.

We can define multiple auxiliary constructors, but they must have different signatures.

Each auxiliary constructor must begin with a call to a previously defined constructor.
 
In the following example, we define an auxiliary constructor that takes one parameter (i.e., “name”) and calls the primary constructor to set the department.

class Employee(var name:String, var department:String){
  def this(name:String){
    this(name,"IT");
  }
}

 
Lets see how both these constructors are invoked in following code:


object HelloWorldScala {
  def main(args: Array[String]) {
    var emp1 = new Employee("John");
    println("Employee Name: " + emp1.name + "Department:" + emp1.department);
    
    var emp2 = new Employee("Dave","Finance");
    println("Employee Name: " + emp2.name + "Department:" + emp2.department);
  }
}

For creating emp1, the auxiliary constructor is invoked. In only takes the name “John” and creates an employee instance with default department “IT”.

for creating the second employee emp2, the primary constructor is invoked.
 

Output

Employee Name: John , Department:IT
Employee Name: Dave , Department:Finance

 

© 2016, https:. All rights reserved. On republishing this post, you must provide link to original post

Leave a Reply.. code can be added in <code> </code> tags