kotlin中interface 与java的接口有什么不同

  1. 直接上代码
class Sub: Sup{

    fun main(x: Any): Unit {
        test1()
        test2()
        Sup.companionObjectTest()
    }
}

interface Sup {
    fun test1(){
        println()
    }

    fun test2(){
        println()
    }

    companion object{
        fun companionObjectTest(){
        }
    }
}
  1. 编译成.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() {} 
}
   }

总结

  1. kotlin接口的方法实现其实是一个内部类
  2. 子类会自动实现接口并调用父类内部类默认实现
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。