您的位置:首页 > 其它

Kotlin 类和对象

2016-03-29 13:56 363 查看
在kotlin声明一个类使用class

在kotlin中类有一个类头的说法,可以指定类型参数,主构造函数等

构造函数也分为主构造函数和二级构造函数

class Student constructor(name: String) {
var name = name;
}

class Stduent2(name: String) {
var name = name;
}

class Student3 {
init {
Log.d("----->", "init");
}
}


主构造函数的constructor可以省略

二级构造函数:constructor

如果类有主构造函数,二级构造函数要直接或者间接的用this关键字使用主构造函数的字段

class Student5 constructor(n: String) {
var name = "";
var age = 0;

constructor(name: String, age: Int) : this(name) {
this.name = name;
this.age = age;
}

}


java 中的构造函数私有化 ,尤其是在做单例的时候:kotlin也可以实现

class Student6 private constructor()
{

}


类的实例:kotlin没有new关键字

var stu=Student("xuan");
var stu2=Student2("xuan2");
var stu3=Student3();
var stu4=Student4("hhhh");
var stu5=Student5("xuan5");
var stu5_1=Student5("xuan5",26);


类的继承:
在kotlin中继承使用:冒号表示 类似于c语言

如果父类没有构造函数:

open class Parent {

}

class Child : Parent() {

}


如果父类有构造函数 ,子类得使用父类的构造参数

open class Parent1(name: String) {

}

class Child2(name: String) : Parent1(name) {

}


多个构造函数包括默认构造函数的情况

open class Parent2() {
constructor(name: String) : this() {

}

constructor(name: String, age: Int) : this() {

}
}

class Child2_1 : Parent2() {

}

class Child2_2 : Parent2 {
constructor(name: String) : super(name);
constructor(name: String, age: Int) : super(name, age);
}

class Child2_3(name: String) : Parent2(name) {

}

class Child2_4(name: String, age: Int) : Parent2(name, age) {

}


复写成员:override注解
open class Apple6 {
open fun say() {
Log.d("----->iphone6 is good", "");
}

//有final修饰的方法子类不能重写
final fun say(name:String)
{

}
}

class Apple6s : Apple6() {
override fun say() {
Log.d("----->iphone6s is good", " 3d touch good");
}
}


在子类中调用父类的方法

class Apple6s : Apple6() {
override fun say() {
super<Apple6>.say();
Log.d("----->iphone6s is good", " 3d touch good");
}
}


抽象类:跟java类似abstract关键字,抽象类默认是open的

抽象类可以没有抽象方法,但是有抽象方法必须是抽象类

abstract class Iphone7
{
abstract fun say();
}

class Iphone7plus:Iphone7()
{
override fun say() {
}
}


属性声明: var 可变变量 val 可读变量

属性的Getter和Setter访问器,kotlin会默认创建setter和getter方法,我们也可以自己定义

class APPLE
{
var name:String="";
get()=field;
set(value){
field="$value";
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: