• kotlin 类


    一、类

    package Aquarium
    
    class Aquarium {
        var width: Int = 20
        var height: Int = 40
        var length: Int = 100
    
        var volume : Int
            get() = return width*height*length/1000
            set(value) { height = (value *1000) / (width * length) }
    
    //    fun volume() : Int {
    //        return width * height * length /1000
    //    }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    Earlier, we created and filtered a list of spices. Spices are much better represented as objects than as simple strings. Because they are objects, we can perform different things with them - such as cooking.

    To recap, let’s make a simple Spice class. It doesn’t do much, but it will serve as the starting point for the next practice.

    Create class, SimpleSpice.
    Let the class be a property with a String for the name of the spice, and a String for the level of spiciness.
    Set the name to curry and the spiciness to mild.
    Using a string for spiciness is nice for users, but not useful for calculations. Add a heat property to your class with a getter that returns a numeric value for spiciness. Use a value of 5 for mild.
    Create an instance of SimpleSpice and print out its name and heat.

    package Aquarium
    
    class SimpleSpice {
        val name = "curry"
        val spiciness = "mild"
        val heat : Int
            get() { return 5}
    }
    
    fun main() {
        val simpleSpice = SimpleSpice()
        println("${simpleSpice.name} ${simpleSpice.heat}")
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    二、默认值

    package Aquarium
    
    class Aquarium(var length: Int = 100, var width: Int = 20, var height: Int = 40) {
    
        var volume : Int
            get() = width*height*length/1000
            set(value) { height = (value *1000) / (width * length) }
    
    //    fun volume() : Int {
    //        return width * height * length /1000
    //    }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    三、Constructors

    package Aquarium
    
    class Aquarium(var length: Int = 100, var width: Int = 20, var height: Int = 40) {
    
        var volume : Int
            get() = width*height*length/1000
            set(value) { height = (value *1000) / (width * length) }
    
        var water = volume * 0.9
    
        constructor(numberOfFish: Int) : this() {
            val water = numberOfFish * 2000
            val tank = water + water * 0.1
            height = (tank / (length * width)).toInt()
        }
    
    //    fun volume() : Int {
    //        return width * height * length /1000
    //    }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    3.1 主构造函数

    class User constructor(name: String) {
        val name: String
        init {
            this.name = name
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    3.2 次要构造函数

    class User
    {
        constructor(name:String)
        {
        }
    //或者
    	init {
    	   print("222")
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    Practice Time
    Let’s improve our SimpleSpice class so that we can have various spices with different levels of spiciness.

    Create a new class, Spice.
    Pass in a mandatory String argument for the name, and a String argument for the level of spiciness where the default value is mild for not spicy.
    Add a variable, heat, to your class, with a getter that returns a numeric value for each type of spiciness.
    Instead of the list of spices as Strings you used earlier, create a list of Spice objects and give each object a name and a spiciness level.
    Add an init block that prints out the values for the object after it has been created. Create a spice.
    Create a list of spices that are spicy or less than spicy. Hint: Use a filter and the heat property.
    Because salt is a very common spice, create a helper function called makeSalt().

    package Aquarium
    
    class SimpleSpice(val name: String, val spiciness: String = "mild") {
        val heat : Int
            get() { return when(spiciness) {
                "mild" -> 1
                "medium" -> 3
                "spicy" -> 5
                "very spicy" -> 7
                "extremely spicy" -> 9
                else -> 0
            }}
    
        init {
            println("Name $name, Spiciness $spiciness, Heat $heat")
        }
    }
    
    fun makeSalt() : SimpleSpice {
        return SimpleSpice("Salt")
    }
    
    fun main() {
        var spices = listOf<SimpleSpice> (
            SimpleSpice("curry", "mild"),
            SimpleSpice("pepper", "medium"),
            SimpleSpice("cayenne", "spicy"),
            SimpleSpice("ginger", "mild"),
            SimpleSpice("red curry", "medium"),
            SimpleSpice("green curry", "mild"),
            SimpleSpice("hot pepper", "extremely spicy")
        )
        var spice = spices.filter { it.heat < 5 }
        makeSalt()
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35

    四、继承

    // All classes in Kotlin have a common superclass Any, that is the default superclass for a class with no supertypes declared:
    
    class Example // Implicitly inherits from Any
    
    // Any has three methods: equals(), hashCode() and toString(). Thus, they are defined for all Kotlin classes.
    
    // By default, Kotlin classes are final: they can’t be inherited. To make a class inheritable, mark it with the "open" keyword.
    
    open class Base //Class is open for inheritance
    
    // To declare an explicit supertype, place the type after a colon in the class header:
    
    open class Base(p: Int)
    
    class Derived(p: Int) : Base(p)
    
    
    // Overriding Methods
    // Kotlin requires explicit modifiers for overridable members and overrides:
    open class Shape {
        open fun draw() { /*...*/ }
        fun fill() { /*...*/ }
    }
    
    class Circle() : Shape() {
        override fun draw() { /*...*/ }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    package Aquarium
    
    import kotlin.math.PI
    
    open class Aquarium(var length: Int = 100, var width: Int = 20, var height: Int = 40) {
    
        open var volume : Int
            get() = width*height*length/1000
            set(value) { height = (value *1000) / (width * length) }
    
        open var water = volume * 0.9
    
        constructor(numberOfFish: Int) : this() {
            val water = numberOfFish * 2000
            val tank = water + water * 0.1
            height = (tank / (length * width)).toInt()
        }
    
    }
    
    class TowerTank() : Aquarium() {
        override var water = volume * 0.8
    
        override var volume: Int
            get() = ( width * height * length / 1000 * PI).toInt()
            set(value) { height = (value * 1000) / (width * length)}
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28

    Let’s talk about books for a moment, those heavy tomes of paper with printed letters.

    Create a class, Book, with a title and an author.
    Add a method, readPage(), that increases the value of a private variable, currentPage, by 1.
    Create a subclass of Book; name it eBook.
    eBook also takes in a format, which defaults to “text”.
    In eBooks, counting words makes more sense than pages. Override the readPage() method to increase the word count by 250, the average number of words per page from typewriter days.

    package Aquarium
    
    open class Book(val title:String, val author: String) {
        private var currentPage = 0
        open fun readPage() {
            currentPage++
        }
    }
    
    class eBook(title:String, author:String,var format:String ="text") : Book(title, author) {
        private var wordsRead = 0
        override fun readPage() {
            wordsRead += 250
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    五、Interface

    package Aquarium
    
    abstract  class AquariumFish {
        abstract val color: String
    }
    
    class Shark : AquariumFish(), FishAction {
        override val color = "gray"
        override fun eat() {
            println("hunt and eat fish")
        }
    }
    
    class Plecostomus : AquariumFish(), FishAction {
        override val color = "gold"
        override fun eat() {
            println("munch on algae")
        }
    }
    
    interface FishAction {
        fun eat()
    }
    
    fun makeFish() {
        val shark = Shark()
        val pleco = Plecostomus()
    
        println("Shark: ${shark.color} \n Plecostomus: ${pleco.color}")
    
        shark.eat()
        pleco.eat()
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33

    Abstract and Interface
    Let’s go back to your spices. Make Spice an abstract class, and then create some subclasses that are actual spices.

    It’s easiest (organizationally) if you make a new package, Spices, with a file, Spice, that has a main() function.
    Copy/paste your Spice class code into that new file.
    Make Spice abstract.
    Create a subclass, Curry. Curry can have varying levels of spiciness, so we don’t want to use the default value, but rather pass in the spiciness value.
    Spices are processed in different ways before they can be used. Add an abstract method prepareSpice to Spice, and implement it in Curry.
    Curry is ground into a powder, so let’s call a method grind(). However, grinding is something that’s not unique to curry, or even to spices, and it’s always done in a grinder. So we can create an Interface, Grinder, that implements the grind() method. Do that now.
    Then add the Grinder interface to the Curry class.
    Delegation
    Using the provided code from the lesson for guidance, add a yellow color to Curry.

    fun main (args: Array<String>) {
       delegate()
    }
    
    fun delegate() {
       val pleco = Plecostomus()
       println("Fish has has color ${pleco.color}")
       pleco.eat()
    }
    
    interface FishAction {
       fun eat()
    }
    
    interface FishColor {
       val color: String
    }
    
    object GoldColor : FishColor {
       override val color = "gold"
    }
    
    class PrintingFishAction(val food: String) : FishAction {
       override fun eat() {
           println(food)
       }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27

    Practice Time
    Abstract and Interface
    Let’s go back to your spices. Make Spice an abstract class, and then create some subclasses that are actual spices.

    1. It’s easiest (organizationally) if you make a new package, Spices, with a file, Spice, that has a main() function.
    2. Copy/paste your Spice class code into that new file.
    3. Make Spice abstract.
    4. Create a subclass, Curry. Curry can have varying levels of spiciness, so we don’t want to use the default value,
      but rather pass in the spiciness value.
    5. Spices are processed in different ways before they can be used. Add an abstract method prepareSpice to Spice,
      and implement it in Curry.
    6. Curry is ground into a powder, so let’s call a method grind(). However, grinding is something
      that’s not unique to curry, or even to spices, and it’s always done in a grinder. So we can create an Interface,
      Grinder, that implements the grind() method. Do that now.
    7. Then add the Grinder interface to the Curry class.

    Delegation
    Using the provided code from the lesson for guidance, add a yellow color to Curry.

    fun main (args: Array<String>) {
       delegate()
    }
    
    fun delegate() {
       val pleco = Plecostomus()
       println("Fish has has color ${pleco.color}")
       pleco.eat()
    }
    
    interface FishAction {
       fun eat()
    }
    
    interface FishColor {
       val color: String
    }
    
    object GoldColor : FishColor {
       override val color = "gold"
    }
    
    class PrintingFishAction(val food: String) : FishAction {
       override fun eat() {
           println(food)
       }
    }
    
    class Plecostomus (fishColor: FishColor = GoldColor):
           FishAction by PrintingFishAction("eat a lot of algae"),
           FishColor by fishColor
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    1. Create an interface, SpiceColor, that has a color property. You can use a String for the color.
    2. Create a singleton subclass, YellowSpiceColor, using the object keyword, because all instances
      of Curry and other spices can use the same YellowSpiceColor instance.
    3. Add a color property to Curry of type SpiceColor, and set the default value to YellowSpiceColor.
    4. Add SpiceColor as an interface, and let it be by color.
    5. Create an instance of Curry, and print its color. However, color is actually a property common to all spices,
      so you can move it to the parent class.
    6. Change your code so that the SpiceColor interface is added to the Spice class and inherited by Curry.
    abstract class Spice(val name: String, val spiciness: String = "mild", color: SpiceColor) : SpiceColor by color {
        abstract fun prepareSpice()
    }
    
    class Curry(name: String, spiciness: String,
                color: SpiceColor = YellowSpiceColor) : Spice(name, spiciness, color), Grinder {
        override fun grind() {
        }
    
        override fun prepareSpice() {
            grind()
        }
    }
    
    interface Grinder {
        fun grind()
    }
    
    interface SpiceColor {
        val color: String
    }
    
    object YellowSpiceColor : SpiceColor {
        override val color = "Yellow"
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25

    六、Data Classes

    package Aquarium.Decorations
    
    fun main(args: Array<String>) {
        makeDecorations()
    }
    
    fun makeDecorations() {
        val d1 = Decorations("grantie")
        println(d1)
    
        val d2 = Decorations("slate")
        println(d2)
    
        val d3 = Decorations("slate")
        println(d3)
    
        println(d1.equals(d2))
        println(d2.equals(d3))
    
        val d4 = d3.copy()
        println(d3)
        println(d4)
    
        val d5 = Decorations2("crystal", "wood", "diver")
        println(d5)
    
        val (rock:String, wood:String, diver:String) = d5
        println(rock)
        println(wood)
        println(diver)
    }
    
    data class Decorations(val rocks: String) {
    
    }
    
    data class Decorations2(val rocks:String, val wood: String, val diver: String) {
    
    }
    
    
    1.Create a simple data class, SpiceContainer, that holds one spice.
    2.Give SpiceContainer a property, label, that is derived from the name of the spice.
    3.Create some containers with spices and print out their labels.
    ```kotlin
    package Aquarium.Decorations
    
    import Practice.Curry
    import Practice.Spice
    
    data class SpiceContainer(var spice: Spice) {
        val label = spice.name
    }
    
    val spiceCabinet = listOf(SpiceContainer(Curry("Yellow Curry", "mild")),
            SpiceContainer(Curry("Red Curry", "medium")),
            SpiceContainer(Curry("Green Curry", "spicy")))
    
    for(element in spiceCabinet) println(element.label)
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60

    七、Special Purpose Classes

    7.1 Singeletons | Objects

    /*
    * SINGLETONS - "Object"
    *
    * To create singleton, use the "object" keyword
    * when you declare you class
    *
    * Anytime you're defining a class that
    * shouldn't be instantiated multiple times
    * you can use the "object" keyword in place of class
    *
    * Kotlin will instantiate exactly one instance of the class
    *
    * Since there can be only one MobyDick, we declare it as an object
    * instead of a class
    * */
    object MobyDickWhale {
        val author = "Herman Melville"
        fun jump () {
            // ...
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    7.2 Enums

    /*
    * ENUMS
    *
    * which lets you enumerate items
    * enums actually define a class
    * and you can give them properties or even methods
    *
    * Enums are like singletons, Kotlin will make
    * exactly one red, exactly one green and exactly one blue
    * there is no way to create more than one color object
    * And, there is not any way to define more colors
    * other then where the enum is declared
    * */
    enum class Color(val rgb: Int) {
        RED(0xFF0000),
        GREEN(0x00FF00),
        BLUE(0x0000FF)
    }
    
    // The most basic usage of enum classes is implementing type-safe enums:
    enum class Direction {
        NORTH, SOUTH, WEST, EAST
    }
    
    // Each enum constant is an object. Enum constants are separated with commas.
    // Since each enum is an instance of the enum class, it can be initialized as:
    
    enum class Color(val rgb: Int) {
            RED(0xFF0000),
            GREEN(0x00FF00),
            BLUE(0x0000FF)
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32

    7.3 Sealed Classes

    /*
    * SEALED CLASS
    *
    * It's a class that can be subclassed
    * but only inside the file which it's declared
    * If you try to subclass it in a different file, you'll get an error
    * This makes sealed classes a safe way to represent a fixed number of types
    *
    * They're great for returning success or error from a network API
    *
    * */
    sealed class Seal {
    
    }
    
    // If we want to create more Seals we have to put them
    // In this file, since the Seal class is in this file!
    // I can't subclass Seal in any other file
    // Since They're all in the same file
    // Kotlin knows statically(at compile time) about all of the subclasses
    class SeaLion: Seal()
    class Walrus: Seal()
    
    /*
    * I can use a "when" statement to check
    * what type of seal I have
    * And If I don't match all of the types of seal
    * Kotlin will give me a compiler error!
    * */
    fun matchSeal(seal: Seal): String {
        return when (seal) {
            is Walrus -> "walrus"
            is SeaLion -> "seaLion"
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35

    You used object in the previous lesson and quiz.

    And now that you know about enums, here’s the code for Color as an enum:

    enum class Color(val rgb: Int) {
       RED(0xFF0000), GREEN(0x00FF00), BLUE(0x0000FF);
    }
    
    • 1
    • 2
    • 3

    In SpiceColor, change the type of color from String to the Color class, and set the appropriate color in YellowSpiceColor.

    Hint: The color code for yellow is YELLOW(0xFFFF00)
    Make Spice a sealed class.

    What is the effect of doing this?
    Why is this useful?

    // You used object in the previous lesson and quiz.
    // And now that you know about enums, here's the code for Color as an enum:
    
    enum class Color(val rgb: Int) {
       RED(0xFF0000), GREEN(0x00FF00), BLUE(0x0000FF);
    }
    
    // In SpiceColor, change the type of color from String to the Color class, and set the appropriate color in YellowSpiceColor.
     // Hint: The color code for yellow is YELLOW(0xFFFF00)
    
    // Make Spice a sealed class.
      // What is the effect of doing this?
      // Why is this useful?
    
    // Solution Code
    interface SpiceColor {
        val color: Color
    }
    
    object YellowSpiceColor : SpiceColor {
        override val color = Color.YELLOW
    }
    
    // Answer Explanation:
    // Making Spice a sealed class helps keep all the spices together in one file. 
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
  • 相关阅读:
    Leetcode 112. 路径总和 java解决给定一个值判断二叉树根节点到叶子节点总和是否相等 算法
    代码最佳实践和指南(二)
    Docker 常用命令
    我的2022面试总结(已拿BAT头条网易滴滴亚马逊offer)
    简介undo log、truncate、​以及undo log如何帮你回滚事物?
    秋招还没Offer怎么办?
    sklearn(一)
    哈工大李治军老师操作系统笔记【9】:内核级线程(Learning OS Concepts By Coding Them !)
    深度神经网络和人工神经网络区别
    flutter 安装流程
  • 原文地址:https://blog.csdn.net/ch122633/article/details/127878679