SoFunction
Updated on 2025-03-08

How to implement static in Java in Kotlin

The static modifier is a very common thing in Java and has many usages. However, there is no such thing in kotlin! So how to replace it? This article summarizes the alternative methods of static in Java in Kotlin.

Summary of the usage of static in java

There are many uses of static in Java, and the most commonly used ones are the following:

  • Static variables and methods
  • Static initialization
  • Static inner class

Let’s take a look at how these scenarios are implemented in kotlin.

Scenario 1: Static variables and methods

Static variables and methods may be the places where we usually use static the most. Let’s first take a look at how Java is done.

Introduction to java static variables and methods:

First, the definition of static variables and methods:

public class StaticTest {
  public static int STATIC_VAR = 0;

  public static void staticMethod(String str){
    (str);
  }
}

Then there are the use of static variables and methods:

StaticTest.STATIC_VAR = 10;
("hello");

Everyone is very familiar with the implementation of Java. Let’s talk about how kotlin is implemented.

The solution of kotlin replacement of static variables and methods

kotlin replaces static variables and methods in Java by introducing the concept of "company objects".

The term "company object" sounds weird, but it is actually very simple: use companion to mark an object in the content of the class. All variables and methods that need to be "static" are placed in this object.

Here is the code that defines the companion object:

class StaticTest {
  companion object{//The names of the companion objects can be specified, but they are generally omitted.    var STATIC_VAR = 0

    fun staticMethod(str: String?) {
      println(str)
    }
  }
}

Next, let’s take a look at how to use companion objects. Companion objects can only be accessed through class names, and the usage methods are similar to Java:

StaticTest.STATIC_VAR = 100
("hello")

What problems does the companion object of kotlin solve?

You may be curious, why does kotlin use such a strange way to solve this problem?

My understanding is for two reasons:

First, the use of companion objects reflects kotlin's consistent design philosophy: everything is an object! Companion objects are also objects! And java static obviously has nothing to do with objects.

Second, companion objects solve a common anti-pattern of java static variables and methods: static methods and variables can be accessed through the object's reference.

Take the example above. Java static variables and methods can be accessed through two methods: class reference and object reference:

//Access through class referenceStaticTest.STATIC_VAR = 10; 
("hello");

//Access through object referenceStaticTest obj = new StaticTest();
obj.STATIC_VAR = 10;
("hello");

It is obviously inappropriate to access static variables and methods through object references. However, in Java, there is no way to avoid this problem from a syntax level.

The companion objects of kotlin can only be accessed through class references, which solves this problem from a syntax level:

//Use class reference accessStaticTest.STATIC_VAR = 100
("hello")
  
//Unable to access using object referenceval obj = StaticTest()
obj.STATIC_VAR = 100 //Compilation error("hello") //Compilation error

In short, every new language feature in kotlin is to fill a certain pit in Java.

Scenario 2: Static initialization

Static initialization in Java can initialize some static variables when the class is loaded, such as:

public class StaticTest {
  public static int STATIC_VAR = 0;
  
  static {
    STATIC_VAR = 100;
    ("in static init");
  }
  
  public static void main(String[] args) {
    (StaticTest.STATIC_VAR);
  }
}

The above code execution result is as follows:

in static init
100

In kotlin, because static variables and methods of Java are implemented in companion objects, and companion objects are also ordinary objects, variable initialization can be achieved through the init method of companion objects. The code is as follows:

class StaticTest {
  companion object{//The names of the companion objects can be specified, but they are generally omitted.    var STATIC_VAR = 0

    init {
      STATIC_VAR = 100
      println("in companion object init")
    }
  }
}

Execute code:

println(StaticTest.STATIC_VAR)

The results are as follows:

in companion object init
100

As you can see, the implementation method of kotlin is more consistent than that of Java. Since everyone is an object, it is initialized through init. In Java, non-static variables are initialized through constructors, while static variables are initialized through static code blocks, which are very inconsistent.

Scenario 3: Static internal class

There are two types of internal classes in Java, ordinary internal classes and static internal classes. The difference between the two is that the former can access variables of external classes, while the latter cannot. At the same time, ordinary inner classes will hold a reference to the outer class, while static inner classes do not.

public class StaticTest {
  
  private int out = 0;
  
  class InnerClass{
    public void InnerClassMethod(){
      out = 100; //Available to access variables of external classes    }
  }

  static class StaticInnerClass{
    public void StaticInnerClassMethod(){
      out = 100; //Compilation error, external class variables cannot be accessed    }
  }
}

There are also two types of inner classes of kotlin: inner classes and nested classes. Syntactically speaking, the difference between binary values ​​is that the former has an additional inner modifier.

Here is a comparison with java:

  • The inner class of kotlin (using the inner modifier) ​​is equivalent to the ordinary inner class of java, which can access external variables and hold references to external objects.
  • kotlin's nested class (without inner modifier) ​​is equivalent to java's static inner class and cannot access external variables

Example of kotlin nested classes:

class StaticTest {
  var out = 0

  inner class InnerClass{
    fun InnerClassMethod(){
      out = 100 //Inner class can access external variables    }
  }
}

Example of kotlin inner class:

class StaticTest {
  var out = 0

  class InnerClass{
    fun InnerClassMethod(){
      out = 100 //Compilation error, nested classes cannot access external variables    }
  }
}

Through comparison, it should be easy to figure out the difference between internal classes and nested classes in kotlin.

Summarize:

The knowledge points of this article are summarized as follows:

  • Static variables and methods of java, using companion object replacement in kotlin
  • Static initialization of java, using init replacement of companion objects in kotlin
  • static inner class of java, use nested classes in kotlin instead

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.