Tuesday, May 19, 2020

Constructor


Constructor :-

  • init Block  //code automatically run
  • Primary Constructor
  • Secondary Constructor  // have more than one secondary constructor

Primary Constructor :-

eg-1

//main function
fun main(args: Array<String>)
{
    val add = Add(5, 6)
    println("The Sum of numbers 5 and 6 is: ${add.c}")
}
//primary constructor
class Add constructor(a: Int,b:Int) //a and b can't be access from main
{
    var c = a+b;
}


eg-2

fun main(args: Array<String>) {
    val emp = employee(18018, "Sagnik")
}
class employee(emp_id : Int , emp_name: String) {
    val id: Int
    var name: String
  
    // initializer block
    init {
        id = emp_id
        name = emp_name
  
        println("Employee id is: $id")
        println("Employee name: $name")
    }
}

output:-
Employee id is: 18018 Employee name: Sagnik


Secondary Constructor :-

Prefix with Constructor
Allow initialization of variables 
Allow to provide some logic to the class as well

eg-1

fun main(args: Array<String>) {
    employee(18018, "Sagnik")
    employee(11011,"Praveen",600000.5)
}
class employee {
  
      constructor (emp_id : Int, emp_name: String ) {
          var id: Int = emp_id
          var name: String = emp_name
          print("Employee id is: $id, ")
          println("Employee name: $name")
          println()
      }
  
       constructor (emp_id : Int, emp_name: String ,emp_salary : Double) {
           var id: Int = emp_id
           var name: String = emp_name
           var salary : Double = emp_salary
           print("Employee id is: $id, ")
           print("Employee name: $name, ")
           println("Employee name: $salary")
       }
}


output:-
Employee id is: 18018, Employee name: Sagnik Employee id is: 11011, Employee name: Praveen, Employee name: 600000.5

No comments:

Post a Comment

Null Safety , Lazy Keyword and LateInit Keyword

Null Safety :- Safe call  ( ? )    use it if you don't mind getting null values Not Null Insertion ( !! )  use if you are sure that val...