Home »
Kotlin
Kotlin Static Variables and Methods
By IncludeHelp Last updated : December 04, 2024
Static Members
Static members are those which are independent of the objects. They are associated with the class not with any particular object. There will be only single copy of static members whether any number of objects are created. So in this article we will learn how to create static members in kotlin.
Static Members in Java
In Java, static members are created using the static
keyword. For example:
Example
class statik{
static intcount;
//constructor
statik(){
count++;
}
static voidgetCount(){
System.out.println("No. of objects="+count);
}
}
public class ExStatic{
public static void main(String[] args) {
//object 1
new statik();
// object 2
new statik();
//method called using class name
statik.getCount();
}
}
Output
No. of objects=2
Static Members in Kotlin
In Kotlin, the companion object is used to create static members for a class.
An object declaration inside a class can be marked with the companion keyword. Members of the companion object can be accessed directly using the class name.
Example of a companion object:
companion object {
var count:Int=0;
}
This is equivalent to:
static int count;
Kotlin Program with Static Members
Here is a Kotlin program where a variable count and a method getCount() are defined inside a companion object. This works similarly to the Java example above.
class statik{
companion object {
// static count
var count:Int=0;
// ataticgetCount()
fun getCount(){
print("No. of objects="+count)
}
}
//constructor
constructor(){
count++
}
}
fun main(args: Array<String>) {
//object 1
statik()
// object 2
statik()
//method called using class name
statik.getCount()
}
Output
No. of objects=2