kotlin 构造函数重载_Kotlin程序| 构造函数重载示例

这篇博客介绍了Kotlin中的构造函数重载概念,包括类可以拥有主构造函数和辅助构造函数,并提供了构造函数重载的程序示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

kotlin 构造函数重载

构造函数重载 (Constructor Overloading)

A Kotlin class has a primary constructor and one or more secondary constructors. When a class has more than one constructor, it will be known as constructor overloading.

Kotlin类具有一个主构造函数和一个或多个辅助构造函数。 当一个类具有多个构造函数时,将称为构造函数重载。

Kotlin中用于构造函数重载的程序 (Program for constructor overloading in Kotlin)

package com.includehelp

//declare Class with Parameterized primary constructor
class ConstructorOverloading(len:Int){

    //Init block, executed when class is instantiated, 
    //before secondary constructor body execution
    init {
        println("Init Block  : $len")
    }

    //Secondary Constructor, 
    //delegate primary constructor with 'this' keyword
    constructor() : this(10) {
        println("Secondary Constructor No Parameter")
    }

    //Parameterized Secondary Constructor, 
    //delegate primary constructor with 'this' keyword
    constructor(name:String):this(name.length){
        println("Secondary Constructor with One Parameter  : $name")
    }

    //Parameterized Secondary Constructor with two parameter,
    //call same class non Parameterized secondary constructor 
    //using 'this()'
    constructor(a:Int, b:Int) : this() {
        println("Secondary Constructor With Two Parameter [$a, $b]")
    }
}


//Main Function, Entry Point of Program
fun main(args:Array<String>){

    //Create instance of class , with Primary Constructor
    ConstructorOverloading(100)

    //Create instance of class, 
    //with no argument secondary constructor
    ConstructorOverloading()

    //Create instance of class, 
    //with one argument secondary constructor
    ConstructorOverloading("India")

    //Create instance of class, 
    //with two argument secondary constructor
    ConstructorOverloading(10,20)
}

Output:

输出:

Init Block  : 100
Init Block  : 10
Secondary Constructor No Parameter
Init Block  : 5
Secondary Constructor with One Parameter  : India
Init Block  : 10
Secondary Constructor No Parameter
Secondary Constructor With Two Parameter [10, 20]


翻译自: https://www.includehelp.com/kotlin/example-of-constructor-overloading.aspx

kotlin 构造函数重载

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值