- 直接上代码
class Sub: Sup{
fun main(x: Any): Unit {
test1()
test2()
Sup.companionObjectTest()
}
}
interface Sup {
fun test1(){
println()
}
fun test2(){
println()
}
companion object{
fun companionObjectTest(){
}
}
}
- 编译成.class之后 反编译成java代码
public final class Sub implements Sup {
public void test2() { Sup.DefaultImpls.test2(this); }
public void test1() { Sup.DefaultImpls.test1(this); }
public final void main(@NotNull Object x) {
Intrinsics.checkParameterIsNotNull(x, "x");
test1();
test2();
Sup.Companion.companionObjectTest();
}
}
public interface Sup {
public static final Companion Companion = Companion.$$INSTANCE;
void test1();
void test2();
public static final class DefaultImpls {
public static void test1(Sup $this) {
boolean bool = false;
System.out.println();
}
public static void test2(Sup $this) {
boolean bool = false;
System.out.println();
} }
public static final class Companion {
static {
Companion companion = new Companion(); $$INSTANCE = companion;
}
public final void companionObjectTest() {}
}
}
总结
- kotlin接口的方法实现其实是一个内部类
- 子类会自动实现接口并调用父类内部类默认实现