Q:

Kotlin program | Example of Primary Constructor

belongs to collection: Kotlin Class and Object Programs

0

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.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Kotlin program | Example of Secondary Constructor... >>
<< Kotlin program | Example of constructor overloadin...