kotlin 构造
来源:互联网 发布:知乎入门级古典音乐 编辑:程序博客网 时间:2024/06/01 08:37
构造函数
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
当Kotlin中的类需要构造函数时,可以有一个主构造函数和多个次构造函数,可以没有次构造函数。主构造函数在类名后。
//常规用法class Person(name: String) {}
当主构造函数有注解或者可见性修饰符,需加 constructor 关键字。
class Personpublic public @Inject constructor(name: String){}
-------------------------------------------------------------------------------------------------------------------------------
1、主构造函数
主构造函数不能包含任何的代码。初始化的代码可以放到以 init 关键字作为前缀的初始化块中:
1、当在主函数中声明后可以当做全局变量使用
注:
1、函数的声明可以是val也可以是var
2、当不在主构造函数中声明又想当全局变量使用,可在类中声明,主函数中声明是简化了其写法。
class Test(name: String){ val name = name //。。。}
- 1
- 2
- 3
-------------------------------------------------------------------------------------------------------------------------------
2、当不在主函数中声明时,只能在初始化块以及属性声明中使用
-------------------------------------------------------------------------------------------------------------------------------
2、次构造函数
1、次构造函数不能有声明 val 或 var
2、如果类有一个主构造函数(无论有无参数),每个次构造函数需要直接或间接委托给主构造函数,用this关键字
class Person { constructor() { } constructor(name: String):this() { } constructor(name: String, age: Int) : this(name) { }}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
class Customer(){ constructor(name: String):this() { } constructor(name: String, age: Int) : this(name) { }}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
-------------------------------------------------------------------------------------------------------------------------------
3、当没有主构造参数时,创建次构造函数
正确使用:
class Customer{ constructor(name: String) { } constructor(name: String, age: Int) : this(name) { }}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
错误使用:
class Customer{ //没有主构造函数,使用委托this()错误 constructor(name: String) : this() { } constructor(name: String, age: Int) : this(name) { }}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
3、构造函数的使用
两种构造函数结果相同,调用时都可直接调用,或传递一个参数或两个参数进行调用
class Test{ init{ test() test2() } fun test(){ Person() Person("李四") Person("李四",18) } fun test2(){ Customer() Customer("李四") Customer("李四",18) }}
阅读全文
0 0
- kotlin 构造
- Kotlin构造函数
- kotlin 构造方法
- Kotlin构造方法
- Kotlin构造函数
- Kotlin中的构造函数
- Kotlin之构造函数
- Kotlin汇总2-类构造,属性,字段
- Kotlin学习笔记(6)-构造器
- Kotlin 构造器和单例模式
- Kotlin学习记录(二)—— Kotlin的变量、属性、类、构造函数、继承、方法
- kotlin的 类,继承,重载,抽象类,构造函数
- 使用Kotlin做一个简单的HTML构造器
- Kotlin入门(12)类的概貌与构造
- Android中Kotlin语言构造函数的使用
- android Kotlin 继承、派生、接口、构造方式,方法、属性重写
- Kotlin
- Kotlin
- Android单击通知栏后返回正在运行的程序并跳转到指定fragment页面
- JS(十一)事件类型
- JavaScript对象【基础】
- form表单的两种提交方式,submit和button的用法
- Android OpenGL显示任意3D模型文件
- kotlin 构造
- 异常处理
- Android多线程-AsyncTask的使用和问题(取消,并行和串行,屏幕切换)
- 【stm32f407】库函数
- 五分钟学会 Kotlin 语法
- 文章标题
- 14 C语言在屏幕上显示内容
- 【Javaweb】Cookie应用——显示用户上次访问网站的时间
- 百度分享