- 直接上代碼
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() {}
}
}
總結(jié)
- kotlin接口的方法實現(xiàn)其實是一個內(nèi)部類
- 子類會自動實現(xiàn)接口并調(diào)用父類內(nèi)部類默認實現(xiàn)