Kotlin object-oriented--class definition method

Kotlin object-oriented--class definition method

kind

Classes in Kotlin are classdeclared using keywords:

class Invoice {

}
Kotlin

A class declaration consists of a class name, a class header (specifying type parameters, primary constructor, etc.) and a class body, enclosed in curly braces. Both the class header and the class body are optional; the curly braces can be omitted if the class has no body. as follows -

class Empty
Kotlin

Constructor

A class in Kotlin can have a primary constructor and one or more secondary constructors. The primary constructor is part of the class header: it follows the class name (and optional type parameters).

class Person constructor(firstName: String) {
}
Kotlin

If the primary constructor does not have any annotations or visibility modifiers, then the constructorkeyword can be omitted:

class Person(firstName: String) {
}
Kotlin

The primary constructor cannot contain any code. Initialization code can be placed in an initializer block, prefixed with a initkeyword:

class Customer(name: String) {
    init {
        logger.info("Customer initialized with value ${name}")
    }
}
Kotlin

Note that the parameters of the primary constructor can be used in the initializer block. They can also be used to declare property initializers in the class body:

class Customer(name: String) {
    val customerKey = name.toUpperCase()
}
Kotlin

In fact, to declare properties and initialize them from the primary constructor, Kotlin has a neat syntax:

class Person(val firstName: String, val lastName: String, var age: Int) {
    // ...
}
Kotlin

Much like regular properties, properties declared in the primary constructor can be multivalued ( var) or read-only ( val).

If the constructor has an annotation or visibility modifier, the constructorkeyword is required and the modifier will precede it:

class Customer public @Inject constructor(name: String) { ... }


Simple example:

// rectangle length and width
class Rect(var longs:Int,var width:Int)

fun main(args: Array<String>) {
    var rect1=Rect(longs=20,width = 10)
    println("Length held: ${rect1.longs}")
    println("Hold width: ${rect1.width}")

}

operation result:

Hold Length: 20
Hold Width: 10



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324506893&siteId=291194637