Kotlin学习笔记(三十六)属性与参数的区别

在Kotlin中,若在类的构造方法用val或者var关键词声明参数,该参数就将成为类的属性,系统会自动生成getter和setter方法,并在构造函数中为相应的属性赋值;若不用val或者var声明参数,该参数就只是类构造器中的参数。

Kotlin代码如下:

class AA(a: Int)

class BB(val b: Int, var c: String)

其对应的Java代码如下:

public final class AA {
   public AA(int a) {
   }
}

public final class BB {
   private final int b;
   private String c;

   public final int getB() {
      return this.b;
   }

   public final String getC() {
      return this.c;
   }

   public final void setC(String var1) {
      this.c = var1;
   }

   public BB(int b, String c) {
      super();
      this.b = b;
      this.c = c;
   }
}

你可能感兴趣的:(Kotlin学习笔记(三十六)属性与参数的区别)