Go straight to code

class Person{
    companion object {
        var age:Int =0

        fun newInstance(age:Int): Person {
            this.age = age
            return Person()
        }
    }
    fun printAge() {
        println("${this} == age:$age")}}Copy the code

In the above code, we define a newInstance(age:Int) method in the Companion Object that modifies the age value and then instantiates a Person instance. The printAge() method in the Person class is used to print the current object and the age value

test

fun main(args: Array<String>) {

    val p1 = Person.newInstance(age = 10)
    val p2 = Person.newInstance(age = 20)
    p1.printAge()
    p2.printAge()
}
Copy the code

Two Person objects p1 and P2 are instantiated through Person.newintance (). They then call their printAge() method. The pits are about to appear, and NAIvely I thought they would print their respective ages, 10 and 20. But… Look at the print result

demo.Person@27c170f0 == age:20
demo.Person@5451c3a8 == age:20
Copy the code

See that? See that? See that. It is true that both objects are instantiated, but their age values are the same. Why is that? Take a look at the Java content converted from the peson.kt and main() methods

public final class Person {
   private static int age;
   public static final Person.Companion Companion = new Person.Companion((DefaultConstructorMarker)null);

   public final void printAge() {
      String var1 = this + " == age:" + age;
      System.out.println(var1);
   }

   public static final class Companion {
      public final int getAge() {
         return Person.age;
      }

      public final void setAge(int var1) {
         Person.age = var1;
      }

      @NotNull
      public final Person newInstance(int age) {
         this.setAge(age);
         returnnew Person(); }... Omit some code.... }} public final class KotlinDemoKt {public static final void main(@notnull String[] args) { Intrinsics.checkParameterIsNotNull(args,"args"); Person p1 = Person.Companion.newInstance(10); Person p2 = Person.Companion.newInstance(20); p1.printAge(); p2.printAge(); }}Copy the code

When calling person.newinstance (), the Companion instance of Person is actually hidden. Companion is a static class and the age variable defined in the Companion Object becomes a private static class in Person. See timeless private static. The problem is a private static problem. So all objects that instantiate and modify age through Person.newinstance () share the same age memory. Oh, end of explanation. After work ~ ~ ~ ~ ~ ~ ~ ~ * *