Object
fun main(args: Array) {
CustomersData.count = 98
CustomersData.typeOfCustomers()
println(CustomersData.typeOfCustomers())
CustomersData.count = 109
println(CustomersData.count)
CustomersData.myMethod("hello")
}
open class MySuperClass {
open fun myMethod(str: String) {
println("MySuperClass")
}
}
object CustomersData: MySuperClass() { // Object Declaration
var count: Int = -1 // Behaves like a STATIC variable
fun typeOfCustomers(): String { // Behaves like a STATIC method
return "Indian"
}
override fun myMethod(str: String) { // Currently, behaving like a STATIC method
super.myMethod(str)
println("object Customer Data: $str")
}
}
When we use keywork object
- Kotlin intenarlly, creates a class and an object/instance
these objects
- Can have properties, methods and initializers
- Can not have Constructors
- as we cannot create object/instance manually
- object can also have super class
- Supports Inheritance
Companion Object
fun main(args: Array) {
MyClass.count // You can print it and check result
MyClass.typeOfCustomers()
}
class MyClass {
companion object {
var count: Int = -1 // Behaves like STATIC variable
@JvmStatic
fun typeOfCustomers(): String { // Behaves like STATIC method
return "Indian"
}
}
}
Companion Objects are same as object but declared within a Class