Kotlin object-oriented--class definition method
kind
Classes in Kotlin are class
declared using keywords:
class Invoice {
}
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
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) {
}
If the primary constructor does not have any annotations or visibility modifiers, then the constructor
keyword can be omitted:
class Person(firstName: String) {
}
The primary constructor cannot contain any code. Initialization code can be placed in an initializer block, prefixed with a init
keyword:
class Customer(name: String) {
init {
logger.info("Customer initialized with value ${name}")
}
}
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()
}
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) {
// ...
}
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 constructor
keyword 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