继上一篇Kotlin基础(一),接下来继续学习Kotlin基础。
//kotlin的静态属性和动态行为
class Girl(var name: String, var chactor: String, var age: Int) {
fun smile(){
println("女生笑了一下")
}
fun cry(){
println("女生哭了,赶紧哄")
}
}
fun main(args: Array<String>) {
//声明Girl这个对象
var girl = Girl("Yorkie","开朗爱笑",18)
println("女生的名字叫:${girl.name}")
println("女生的性格是:${girl.chactor}")
println("女生的年龄是:${girl.age}")
girl.smile()
girl.cry()
}
父类:
//需要添加open关键字才可以被继承
open class Father{
open var chactor:String ="性格内向";
open var appearance:String = "憨厚老实";
var height:String = "人高马大";
open fun action(){
println("性格内向,不喜欢跟陌生人接触")
}
}
子类:
//子类,继承了父类Father类
class Son :Father(){
override var chactor:String ="性格开朗";
override var appearance:String = "英俊潇洒";
override fun action(){
println("性格开朗,与别人非常健谈")
}
}
测试类Test:
fun main(args: Array) {
var son = Son()
println("儿子的性格:${son.chactor}")
println("儿子的样貌:${son.appearance}")
println("儿子的身高:${son.height}")
son.action()
}
抽象类:
//抽象类
abstract class HuMan{
abstract fun sport()
abstract fun girl()
}
接口:
//接口
interface IMan{
fun eat()
fun sleep()
}
子类:
//子类,继承抽象类HuMan,实现接口IMan
class Man : HuMan(), IMan {
override fun eat() {
println("我是男人,我当然会吃东西")
}
override fun sleep() {
println("我是男人,我当然也会睡觉")
}
override fun sport() {
println("我是男人,我喜欢运动")
}
override fun girl() {
println("我是男人,我也喜欢看美女")
}
}
测试类Test:
fun main(args: Array<String>) {
//实例化一个Man的对象
var man = Man()
//调用方法
man.eat()
man.sleep()
man.sport()
man.girl()
}
接口:
interface ICreatApp{
fun programming()
}
程序员类:
//程序员,object关键字代表这个类已经是单例模式
object Programmer:ICreatApp{
override fun programming(){
println("低头专注的打代码")
}
}
经理类:
//经理委托程序员
class Manager:ICreatApp by Programmer{
override fun programming(){
println("我是经理,我收到老板的指令,要编写一个APP")
Programmer.programming()
println("我是看着程序员把这个APP给写完的")
}
}
测试类Test:
fun main(args: Array<String>) {
var manager = Manager()
manager.programming()
}
//枚举类
enum class Week{
Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday
}
fun main(args: Array<String>) {
println(Week.Monday)
println(Week.Tuesday.ordinal)
}
//印章类,孩子有女儿和儿子
sealed class Kid{
fun sayHello(){
println("你们好,我还是个孩子")
}
class Son():Kid()
class Daughter():Kid()
}
测试类Test:
fun main(args: Array<String>) {
//实例化三个对象
var k1:Kid = Kid.Son()
var k2:Kid = Kid.Daughter()
var k3:Kid = Kid.Son()
var list = listOf<Kid>(k1,k2,k3)
for(k in list){
if(k is Kid.Son){
k.sayHello()
}
}
}