Kotlin program | Example of Primary Constructor

Kotlin | Primary Constructor: Here, we are implementing a Kotlin program to demonstrate the example of primary constructor.
Submitted by IncludeHelp, on June 12, 2020

Primary Constructor

  • A Kotlin class have Primary constructor and one or more Secondary constructor.
  • In Kotlin, Primary Constructor is the Part of Class Header.
  • Syntax:
    class <Class Name> constructor(<optional Parameters>){
        // Class Body
    }
    
  • The default visibility of the constructor will be public.
  • Parameter of the primary constructor can be used in property initializer, declared in the class body.

Program to demonstrate the example of Primary Constructor in Kotlin

// Declare Class, with Primary Constructor keyword, 
// with one Parameter
class Dog constructor(name:String){
    // Used Constructor Parameter to initialize property
    // in class body
    // String? for nullable property, 
    // so property also contain null
    private var name:String?=name
    fun getDogName(): String?{
        return name
    }
}

/*
    A) Constructor Keyword can be omitted if constructor 
    does not have annotations and visibility modifiers.
*/
// Declare class, omitted Constructor Keyword
class Horse (name:String){
    // Used Constructor Parameter to 
    // initialize property in class body
    private var name:String =name.toUpperCase()

    fun getHorseName(): String?{
        return name
    }
}


/*
    A) Kotlin has concise Syntax to declaring property 
    and initialize them from primary constructor.
    class Employee(var empName:String, val salary:Int)
    B) same way as regular properties declaration, 
    properties declare in primary constructor can be 
    var (mutable) or val (immutable)
 */
 
// Declare class, Properties declare  in primary constructor
class Cat(private var name:String, private val age:Int){
    fun setCatName(name:String){
        this.name =name
    }
    fun printData(){
        println("Name : $name and Age : $age")
    }
}

// Main Function, entry Point of Program
fun main(args:Array<String>){
    // Create Dog Class Object
    val dog = Dog("tommy")
    println("Dog Name : ${dog.getDogName()}")

    // Create Horse Class object
    val horse =Horse("Chetak")
    println("Horse Name : ${horse.getHorseName()}")

    // Create Cat Class object
    val cat = Cat("Katrina",32)
    cat.printData()
    cat.setCatName("Micy")
    cat.printData()
}

Output:

Dog Name : tommy
Horse Name : CHETAK
Name : Katrina and Age : 32
Name : Micy and Age : 32


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.