1 匿名类
1)无继承
fun main() {var obj = object {var name: String = "zhang"override fun toString(): String {return name}}println(obj) // zhang
}
2)有继承
fun main() {var obj = object: People {var name: String = "zhang"override fun play() {println("play, $name")}}obj.play() // play, zhang
}interface People {fun play()
}
2 单例
2.1 案例一
1)object 单例
fun main() {var singleton = Singletonprintln(singleton)
}object Singleton {var name = "zhang"override fun toString(): String {return return name}
}
2)对应的 java 类
Singleton.java
public final class Singleton {private static String name;public static final Singleton INSTANCE;static {INSTANCE = new Singleton();name = "zhang";}private Singleton() {}public final String getName() {return name;}public final void setName(String var1) {name = var1;}public String toString() {return name;}
}
java 中调用如下。
Singleton singleton = Singleton.INSTANCE;
System.out.println(singleton);
2.2 案例二
1)object 单例
fun main() {var stu = Student.Tools.create("zhang")println(stu) // zhangprintln(Student.Tools.age) // 15
}class Student(var name: String) {object Tools {var age: Int = 15fun create(name: String): Student {return Student(name)}}override fun toString(): String {return name}
}
2)对应的 java 类
Student.java
public final class Student {private String name;public Student(String name) {this.name = name;}public final String getName() {return this.name;}public final void setName(String var1) {this.name = var1;}public String toString() {return this.name;}public static final class Tools {private static int age;public static final Tools INSTANCE;static {INSTANCE = new Tools();age = 15;}private Tools() {}public final Student create(String name) {return new Student(name);}public final int getAge() {return age;}public final void setAge(int var1) {age = var1;}}
}
java 中调用如下。
Student stu = Student.Tools.INSTANCE.create("zhang");
System.out.println(stu);
System.out.println(Student.Tools.INSTANCE.getAge());
3 伴生类
1)companion object
fun main() {var stu = Student.create("zhang")println(stu) // zhangprintln(Student.age) // 15
}class Student(var name: String) {companion object Tools {var age: Int = 15fun create(name: String): Student {return Student(name)}}override fun toString(): String {return name}
}
2)对应的 java 类
Student.java
public final class Student {private String name;private static int age = 15;public static final Tools Tools = new Tools(();public Student(String name) {this.name = name;}public final String getName() {return this.name;}public final void setName(String var1) {this.name = var1;}public String toString() {return this.name;}public static final class Tools {private Tools() {}public final Student create(String name) {return new Student(name);}public final int getAge() {return Student.age;}public final void setAge(int var1) {Student.age = var1;}}
}
java 中调用如下。
Student stu = Student.Tools.create("zhang");
System.out.println(stu);
System.out.println(Student.Tools.getAge());