今天我们来看kotlin中的类和接口,内容有kotlin对象、构造方法、属性、继承,接口、抽象类,修饰符和扩展函数
首先我们先来说一下修饰符
/**
* 修饰符
* open:是否可被继承
* final:是否可被覆盖
* 接口和抽象类是不同的,接口可以把属性和方法进行抽象化,不对其进行具体的赋值和实现,而非抽象类是不可以的
* 接口默认是加上open修饰符的,不需要手动添加
*/
/**
* private:只在类内部可见
* protected:类内部可见,并且子类中可见
* internal:能见到类声明的本模块内的客户端都可见
* public:能见到类声明的任何客户端都可见
*/
/**
* kotlin对象
*/
class Friend{
var name: String = ""
var age: Int = 0
var wearGalesses : Boolean = false
var colorOfHair:String = ""
var owe:Int = 0
fun isAdult():Boolean = if (age >= 18) true else false
fun printInfomation() = println("I have a friend,his name is ${name},he ${if (wearGalesses) "wear" else "down't wear"} a glasses and his color of hair is ${colorOfHair},he owe me ${owe} money")
}
fun main(args: Array<String>) {
val friend_first = Friend()
friend_first.name = "zhangsan"
friend_first.wearGalesses = true
friend_first.colorOfHair = "black"
friend_first.owe = 100
friend_first.printInfomation()
}
/**
* 构造方法
*
* 在主构造函数中,constructor这个关键字可以省略(如果构造函数有注解或可见性修饰符,那么constructor是不能省略的)
* 主构造函数里不能包含任何代码,初始化代码使用init
*/
class Friend2(name:String, age:Int){
val name:String = name
val age:Int = age
init {
println("You have a Friend name $name")
}
}
/**
* 次构造函数
* constructor关键字必不可少
*/
class Friend3{
val name:String
val age:Int
constructor(name: String,age: Int){
this.name = name
this.age = age
}
}
/**
* 委托
*/
class Friend4(name: String,age: Int){
constructor(name: String,age: Int,child:Friend4):this(name, age){
// this.parent=child.parent
child.parent = this
}
val name = name
val age = age
var parent:Friend4?=null
}
//主构造函数参数:名字、年龄
class Person(name: String,age: Int){
/**
* 次构造函数参数:名字、年龄、父母、孩子
*/
constructor(name: String,age: Int,parents:MutableList<Person>,child:MutableList<Person>):this(name, age){
parents.forEach { it.children.add(this) }
children.forEach { it.parents.add(this) }
this.parents.addAll(parents)
this.children.addAll(child)
}
val name = name
val age = age
var parents = mutableListOf<Person>()
var children = mutableListOf<Person>()
//显式关羽个人的名字与年龄信息
fun showPersonalInformation() = println("name:${name},age:${age}")
//显式关于孩子的名字与年龄信息
fun showChildrenInfomation() = children.forEach { it.showPersonalInformation() }
//显式关于父母的名字与年龄信息
fun showParentsInformation() = parents.forEach { it.showPersonalInformation() }
}
fun main(args: Array<String>) {
val friend_first = Friend2("zhangsan",18)
Friend4("zhangsan",18,Friend4("zhangsan",20))
val bady = Person("MingHong",3)
val parent1 = Person("DaMing",50)
val parent2 = Person("DaHong",45)
var child1 = Person("XiaoMing",18, mutableListOf(parent1,parent2), mutableListOf(bady))
var child2 = Person("XiaoHong",20, mutableListOf(parent1,parent2), mutableListOf(bady))
child1.showParentsInformation()
child1.showChildrenInfomation()
bady.showParentsInformation()
}
/**
* kotlin中的属性
*/
class NumberCompution(val num1:Int,val num2:Int,var operator:(Int,Int)-> Int){
fun operation(){
println("Operation Result:${operator(num1,num2)}")
}
}
class Person2(age:Int){
var age = age
val isAudlt:Boolean
get() = age >= 18
var addAge:Int
get() = 0
set(value) {
age += value
}
}
fun main(args: Array<String>) {
val numComp = NumberCompution(10,20,{x,y -> x + y})
numComp.operation()
numComp.operator = {x,y -> x * y}
numComp.operation()
}
/**
* 继承
*/
//demo1
open class person{
var name:String = ""
var age :Int = 0
var height: Int = 0
var likeFood:String = ""
var costByMonth:Int = 0
fun printInformation() = println("name:${name},age:${age},height:${height},likeFood:${likeFood},costByMonth:${costByMonth}")
}
class Student: person(){
var teacherNumbers: Int = 0
var schoolName:String = ""
}
class Worker: person(){
var nameOfWorkPlace: String = ""
var salary: Int = 0
}
//demo2 主构造函数
open class person2(name:String,age:Int,height:Int,likeFood:String,constByMonth:Int){
val name:String = name
val age:Int = age
val height:Int = height
val likeFood:String = likeFood
val constByMonth:Int = constByMonth
fun printInformation() = println("name:${name},age:${age},height:${height},likeFood:${likeFood},constByMonth:${constByMonth}")
}
class Student2(name: String,age: Int,height: Int,likeFood: String,constByMonth: Int,teacherNumbers:Int,schoolName:String):person2(name, age, height, likeFood, constByMonth){
val teacherNumbers:Int = teacherNumbers
val schoolName:String = schoolName
}
//demo3 超类没有主构造函数,只有次构造函数
open class person3{
constructor(name: String,age: Int,height: Int,likeFood: String,costByMoth:Int){
this.name = name
this.age = age
this.height = height
this.likeFood = likeFood
this.costByMoth = costByMoth
}
var name:String = ""
var age:Int = 0
var height :Int = 0
var likeFood:String = ""
var costByMoth:Int = 0
open fun printInformation() = println("name:${name},age:${age},height:${height},likeFood:${likeFood},constByMonth:${costByMoth}")
}
class Student3:person3{
constructor(name: String,age: Int,height: Int,likeFood: String,costByMoth: Int,teacherNumbers: Int,schoolName: String):super(name, age, height, likeFood, costByMoth){
this.teacherNumbers = teacherNumbers
this.schoolName = schoolName
}
var teacherNumbers: Int = 0
var schoolName: String = ""
override fun printInformation() {
super.printInformation()
}
}
fun main(args: Array<String>) {
val student = Student()
student.name = "zhangsan"
student.age = 20
student.schoolName = "ZheJiang Nonglin"
student.printInformation()
//demo2
val student2 = Student2("XiaoMing",20,180,"beef",300,10,"ZheJiang")
student2.printInformation()
}
/**
* 抽象类、重写和重载
*
*
*/
abstract class News{
var origin = "reporter"
abstract var content:String
abstract fun newslength():Int
}
class SchoolNews:News(){
override var content: String = ""
override fun newslength(): Int = content.length
}
//重写
open class A{
open var character:String=""
open fun printSign(content:String) = println(character.toLowerCase())
}
class B : A(){
override var character: String = "hahaha"
override fun printSign(content: String) = println(character.toUpperCase())
}
//重载
class C{
fun printSign(content: String) = println(content.toLowerCase())
fun printSign(content: String,upOrLow:String) = when(upOrLow){
"up" -> println(content.toUpperCase())
"low" -> println(content.toLowerCase())
else -> println(content.toLowerCase())
}
}
fun main(args: Array<String>) {
val scn = SchoolNews()
scn.content = "today,we are learning Kotlin"
println(scn.newslength())
println(scn.origin)
}
/**
* 接口
*/
interface Common_Compution{
fun add()
fun subtract()
fun multiply()
fun divide()
fun printAllCommonResult(){
println("add:");add()
println("subtract:");subtract()
println("multiply:");multiply()
println("divide:");divide()
}
}
interface Advanced_Compution{
fun pow(up: Int)
}
class Compution(num1:Double,num2:Double):Common_Compution,Advanced_Compution{
val num1 = num1
val num2 = num2
override fun add() {
println(num1 + num2)
}
override fun subtract() {
println(num1 - num2)
}
override fun multiply() {
println(num1 * num2)
}
override fun divide() {
println(num1 / num2)
}
override fun pow(up: Int) {
var num1_result = 1.0
var num2_result = 1.0
for (i in 1..up){
num1_result *= num1
num2_result *= num2
}
println("num1:${num1_result},num2:${num2_result}")
}
}
//接口声明属性
interface PersonInterface{
var name: String
var age: Int
var height: Double
var weight: Double
}
class Person:PersonInterface{
override var name: String = "xxx"
override var age: Int = 0
override var height: Double = 0.0
override var weight: Double = 0.0
}
interface Apple{
fun printSelf()
fun give() = println("give you an apple")
}
interface Banana{
fun printSelf() = println("banana")
fun give() = println("give you a banana")
}
class AppleBanana:Apple,Banana{
override fun printSelf() = println("apple banana")
override fun give() {
super<Apple>.give()
super<Banana>.give()
}
}
fun main(args: Array<String>) {
val num = Compution(3.0,2.0)
num.printAllCommonResult()
val ab = AppleBanana()
ab.give()
}
/**
* 扩展函数
* 扩展函数是静态解析的,类内部方法是动态解析的
* 一个类中,如果它内部的方法和扩展函数的名称相同,参数的类型和数量也相同,当调用这个方法或函数时,优先执行它内部的方法
*/
//扩展函数
class Say{
fun sayHi() = println("Hi!")
fun sayBye() = println("Bye!")
}
fun Say.sayGreat() = println("Great")
fun Int.sayHello() = println("Hello,I am ${this}")
fun MutableMap<String,Int?>.addNotNull(key:String,value:Int?){
if (value != null){
this[key] = value
}
}
fun main(args: Array<String>) {
val say = Say()
say.sayGreat()
1.sayHello()
val map = mutableMapOf<String,Int?>()
map.addNotNull("one",2)
map.addNotNull("two",null)
map.addNotNull("three",3)
println(map)
}