Kotlin Notes Object-Oriented (5)
Kotlin note data type (1) Kotlin note string (2) Kotlin note operator (3) Kotlin note function (4)
Article directory
foreword
Object-oriented is more important, to fully understand the three characteristics of object-oriented
Encapsulation: Encapsulation prevents external visitors from arbitrarily accessing the internal data of the object, hides the internal details of the object, and only retains a limited external interface. External visitors do not need to care about the internal details of the object, making it easy to manipulate objects
Inheritance: Inheritance means that the subclass inherits the characteristics and behaviors of the parent class, so that the subclass object (instance) has the instance fields and methods of the parent class, or the subclass inherits the method from the parent class, so that the subclass has the same behavior as the parent class
Polymorphism: It means that the same method of a class instance (object) has different manifestations in different situations. Polymorphism enables objects with different internal structures to share the same external interface. This means that although the specific operations are different for different objects, they (those operations) can be invoked in the same way through a common class.
Tip: The following is the text of this article, and the following cases are for reference
1. Object-oriented mind map
Example: pandas is a NumPy-based tool created to solve data analysis tasks.
Two, attributes
Properties in Kotlin can be declared in classes, called member properties. Properties can also be outside the class, similar to
top-level functions, called top-level properties. In fact, top-level properties are global variables. property declaration structure
var|val 属性名 [ : 数据类型] [= 属性初始化 ]
[getter访问器]
[setter访问器]
1. Lazy initialization of properties
Using lateinit
the keyword , the attribute must be initialized when the class is declared, and the attribute initialization can be delayed by using this keyword
fun main(args: Array<String>) {
var student3=Student3()
student3.name="zyb"
println(student3.name)
}
class Student3{
var score:Float=10.0f
lateinit var name:String
}
2. Delegated properties
Use the keyword by to delegate the get/set method of the property to the object
class Student3{
var name:String by Teacher()
}
class Teacher{
var name:String="张三"
operator fun getValue(thisRef: Any, property: KProperty<*>):String{
return this.name
}
operator fun setValue(thisRef: Any,property: KProperty<*>,value:String){
this.name=value
}
}
3. Lazy loading attributes
Use the keyword by lazy
lazy- loaded properties must be val, and lazy-initialized properties must be var
fun main(args: Array<String>) {
var dog=Dog()
println(dog.info)
}
class Dog{
var name:String="金毛"
var age:Int=2
val info:String by lazy{
"name:$name age:$age"
}
}
4. Observable properties
Listen for property changes
fun main(args: Array<String>) {
var cat=Cat()
cat.age=1
}
class Cat{
var age:Int by Delegates.observable(0){
property, oldValue, newValue ->
println("old:$oldValue new:$newValue")
}
}
3. Constructor
A constructor is a special function that is called when the class is initialized
1. Primary constructor declaration
full primary constructor declaration
class Pig constructor(name:String,age:Int){
var name:String
var age:Int
init {
this.name=name
this.age=age
}
}
Shorthand primary constructor declaration
class Pig (var name:String,var age:Int)
constructor cannot be omitted when modified with modifiers
class Pig private constructor(var name:String,var age:Int)
The primary constructor can also set default values
class Pig (var name:String="品种",var age:Int=2)
2. The secondary constructor declaration uses
fun main(args: Array<String>) {
var cat=Pig("大猪")
var pig=Pig("小猪",18,20.0f)
var pig1=Pig()
}
class Pig (var name:String,var age:Int){
var price:Float=10.0f
constructor(name:String,age:Int,price:Float) :this(name,age){
this.price=price
}
constructor(name: String):this(name,12,12.0f)
constructor()
}
3. Default constructor
If the constructor is not explicitly declared, the system will automatically generate a parameterless constructor
4. Expansion
1. Extended attributes
fun main(args: Array<String>) {
var pig =Pig("小猪",2,20.0f)
println(pig.info)
}
var Pig.info:String
get() {
return "${this.name} 年龄 :${this.age} 价格:${this.price}"
}
set(value) {
}
class Pig (var name:String,var age:Int){
var price:Float=10.0f
constructor(name:String,age:Int,price:Float) :this(name,age){
this.price=price
}
constructor(name: String):this(name,12,12.0f)
}
2. Extension function
fun main(args: Array<String>) {
var pig =Pig("小猪",2,20.0f)
println(pig.getInfoPig())
}
fun Pig.getInfoPig():String{
return "${this.name} 年龄 :${this.age} 价格:${this.price}"
}
class Pig (var name:String,var age:Int){
var price:Float=10.0f
constructor(name:String,age:Int,price:Float) :this(name,age){
this.price=price
}
constructor(name: String):this(name,12,12.0f)
}
3. Infix function
To define an infix operator is to declare a function modified by the infix keyword. This function can only have one
parameter. This function cannot be a top-level function, but only a member function or an extension function.
fun main(args: Array<String>) {
var pig =Pig("小猪",2,20.0f)
pig getNamePig "pig"
}
class Pig (var name:String,var age:Int){
var price:Float=10.0f
constructor(name:String,age:Int,price:Float) :this(name,age){
this.price=price
}
constructor(name: String):this(name,12,12.0f)
infix fun getNamePig(name:String){
println(name)
}
}
4. Member priority
Priority member functions of the same function are greater than extension functions
5. Modifiers
visibility | Modifier | class member declaration | top-level declaration |
---|---|---|---|
public | public default | visible everywhere | visible everywhere |
internal | internal | visible in the module | visible in the module |
Protect | protected | visible in subclasses | cannot be used in top-level declarations |
private | private | visible in class | visible in the file |
6. Data class
fun main(args: Array<String>) {
var person =Person1("zyb",1)
println(person)
}
data class Person1(var name:String,var age: Int)
7. Enumeration
Use of enumeration classes
fun main(args: Array<String>) {
var flag=WeekDays.MONDAY
when(flag){
WeekDays.MONDAY -> println("星期一")
WeekDays.TUESDAY -> println("星期二")
WeekDays.WEDNESDAY -> println("星期三")
WeekDays.THURSDAY -> println("星期四")
else -> println("星期五")
}
}
//最简单形式的枚举类
enum class WeekDays {
// 枚举常量列表
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY
}
enum class constructor
fun main(args: Array<String>) {
println(WeekDays.MONDAY)
}
//最简单形式的枚举类
enum class WeekDays (private var names:String,private var index:Int){
// 枚举常量列表
MONDAY("星期一",2), TUESDAY("星期二",3), WEDNESDAY("星期三",4), THURSDAY("星期四",5), FRIDAY("星期五",5);
override fun toString(): String {
return "$names:$index"
}
}
8. Nested classes
The inner class cannot access the properties and methods of the outer class, and the outer class can initialize the inner class and access the properties and methods
class A{
var index:Int=0
fun sayA(){
println(index)
}
class B{
var indexB:Int=1
fun sayB(){
println("B")
}
}
fun initB(){
var b=B()
b.indexB
b.sayB()
}
}
Nine, inner class
class Out{
var age:Int=10
fun getAges():Int=age
inner class Inner{
var innerName:String="Inner"
fun getOutInfo():String{
println(getAges())
return "$innerName $age"
}
}
fun test(){
var inner=Inner()
inner.getOutInfo()
}
}
10. The object keyword
1. Object expression
Java-like anonymous objects
fun main(args: Array<String>) {
setOnclickLister( object : OnclickLister{
override fun onclick() {
println("点击了")
}
})
}
fun setOnclickLister(onclickLister: OnclickLister){
onclickLister.onclick()
}
interface OnclickLister{
fun onclick()
}
2. Object declaration
Declares that the object is a singleton
object Sun{
}
3. Companion object
There is no static keyword in Kotlin. Therefore, to use static methods, static properties, and static code blocks, they can only be declared companion object
by
fun main(args: Array<String>) {
var fish =Fish()
println(fish.name)
println(Fish.getVersin())
}
class Fish{
var name:String="zhang"
constructor(){
println("构造方法")
}
companion object{
var version:Int=10
fun getVersin():Int{
return version
}
init {
println("静态代码块")
}
}
}