How to implement static in Java in kotlin

Static modifier is a very common thing in Java, and there are many uses. However, there is no such thing in kotlin! How to replace it? This article summarizes several common uses of static in Java and their alternatives in kotlin.

Usage Summary of static in Java

There are many uses of static in Java. The most commonly used are as follows:

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 where we usually use static most. Let's take a look at how it is done in Java.

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){
    System.out.println(str);
  }
}

Then the use of static variables and methods:

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

Everyone is very familiar with the implementation of Java. Let's focus on how kotlin is implemented.

Kotlin's alternative to static variables and methods

Kotlin replaces static variables and methods in Java by introducing the concept of "associated object".

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

The following is the code to define the associated object:

class StaticTest {
  companion object{//伴生对象是可以指定名字的,不过一般都省略掉。
    var STATIC_VAR = 0

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

Next, let's look at how to use the associated object. The associated object can only be accessed through the class name. The use method is similar to Java:

StaticTest.STATIC_VAR = 100
StaticTest.staticMethod("hello")

What problem does kotlin's companion solve?

You may wonder, why did kotlin solve this problem in such a strange way?

My understanding is that there are two reasons:

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

Second, the companion object solves a common anti pattern of Java static variables and methods: static methods and variables can be accessed through object references.

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

//通过类引用访问
StaticTest.STATIC_VAR = 10;
StaticTest.staticMethod("hello");

//通过对象引用访问
StaticTest obj = new Statictest();
obj.STATIC_VAR = 10;
obj.staticMethod("hello");

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

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

//使用类引用访问
StaticTest.STATIC_VAR = 100
StaticTest.staticMethod("hello")

//不能使用对象引用访问
val obj = Statictest()
obj.STATIC_VAR = 100 //编译错误
obj.staticMethod("hello") //编译错误

In short, every new language feature in kotlin is to fill a hole 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;
    System.out.println("in static init");
  }

  public static void main(String[] args) {
    System.out.println(StaticTest.STATIC_VAR);
  }
}

The execution result of the above code is as follows:

In kotlin, because the static variables and methods of Java are implemented in the associated object, and the associated object is also an ordinary object, the initialization of variables can be realized through the init method of the associated object. The code is as follows:

class StaticTest {
  companion object{//伴生对象是可以指定名字的,不过一般都省略掉。
    var STATIC_VAR = 0

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

Execution code:

println(StaticTest.STATIC_VAR)

The results are as follows:

It can be seen that the implementation of kotlin is more consistent than that of Java. Since everyone is an object, they are initialized through init. In Java, non static variables are initialized through constructors, while static variables are initialized through static code blocks. The two are very inconsistent.

Scenario 3: static internal classes

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 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; //可以访问外部类的变量
    }
  }

  static class StaticInnerClass{
    public void StaticInnerClassMethod(){
      out = 100; //编译错误,不可以访问外部类的变量
    }
  }
}

Kotlin has two inner classes: inner class and nested class. Grammatically, the difference between two values is that the former has an inner modifier.

The following is a comparison with Java:

Examples of kotlin nested classes:

class StaticTest {
  var out = 0

  inner class InnerClass{
    fun InnerClassMethod(){
      out = 100 //内部类可以访问外部变量
    }
  }
}

Examples of kotlin inner classes:

class StaticTest {
  var out = 0

  class InnerClass{
    fun InnerClassMethod(){
      out = 100 //编译错误,嵌套类不可以访问外部变量
    }
  }
}

By comparison, it should be easy to understand the difference between inner classes and nested classes in kotlin.

Summary:

The knowledge points of this paper are summarized as follows:

The above is the whole content of this article. I hope it will help you in your study, and I hope you will support us a lot.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>