Scala

27 / 52
   

Scala - Classes with multiple constructors

Classes have multiple constructors i.e. you can instantiate them in different ways.
In below example, a car be created with make/model/year or just with make/model.
Take note of the class method dispCar and function dispCarDetails to display the information of a car.

import java.io._

class Car() {
    var make: String = "";
    var model: String = "";
    var year: Int = 0;
    var color = "";

    def this(makeOfCar: String, modelOfCar: String, yearOfCar: Int) {
        this()
        println("Creating new car object per first constructor")
        this.make = makeOfCar;
        this.model = modelOfCar;
        this.year = yearOfCar;
        this.color = "Black";
    }

    def this(makeOfCar: String, modelOfCar: String) {
        this()
        println("Creating new car object per second constructor")
        this.make = makeOfCar;
        this.model = modelOfCar;
        this.year = 1990;
        this.color = "Blue";
    }

    def dispCar() {
        println("Car details:" + this.make + " " + this.model + " " + this.year + " " + this.color)
    }
}


object Demo {
    def main(args: Array[String]) {
        var car1 = new Car("Honda", "City", 1996);
        var car2 = new Car("Honda", "Accord");
        var car3 = new Car("Honda", "Amaze", 2015);
        println("")
        println("Displaying car info in main program:")
        println("Car details:" + car1.make + " " + car1.model + " " + car1.year + " " + car1.color)
        println("Car details:" + car2.make + " " + car2.model + " " + car2.year + " " + car2.color)
        println("Car details:" + car3.make + " " + car3.model + " " + car3.year + " " + car3.color)
        println("")
        println("Displaying car info via function:")
        dispCarDetails(car1)
        dispCarDetails(car2)
        dispCarDetails(car3)
        println("")
        println("Display car info via class func:")
        car1.dispCar()
        car2.dispCar()
        car3.dispCar()
    }

    def dispCarDetails(car:Car) = {
        println("Car details via func:" + car.make + " " + car.model + " " + car.year + " " + car.color)
    }

}