Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/kotlin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Interface 科特林抽象体法_Interface_Kotlin_Abstract - Fatal编程技术网

Interface 科特林抽象体法

Interface 科特林抽象体法,interface,kotlin,abstract,Interface,Kotlin,Abstract,如前所述:如果接口中的函数没有主体,那么默认情况下它是抽象的。但并没有关于接口与主体的功能 例如: interface MyInterface { fun foo() { print("Something") } fun bar() } fun main(args: Array<String>) { println(MyInterface::foo.javaMethod) println(MyInterface::bar.javaMethod) }

如前所述:如果接口中的函数没有主体,那么默认情况下它是抽象的。但并没有关于接口与主体的功能

例如:

interface MyInterface {
    fun foo() { print("Something") }
    fun bar()
}

fun main(args: Array<String>) {
    println(MyInterface::foo.javaMethod)
    println(MyInterface::bar.javaMethod)
}

如何可能,具有定义体的方法是抽象的?

这与Kotlin接口中默认方法的实现方式有关。界面中的
foo
bar
方法实际上都是抽象的

但是,接口中有一个内部类,看起来像这样(简化):

这个类包含您在接口中为其提供主体的任何函数的默认实现

然后,如果您创建了一个实现此接口的类,并且没有重写
foo
方法:

class MyClass: MyInterface {
    override fun bar() {
        println("MyClass")
    }
}
然后自动生成一个,它只调用
DefaultImpls
中的实现:

public final class MyClass implements MyInterface {
   public void bar() {
      System.out.println("MyClass");
   }
   public void foo() {
      MyInterface.DefaultImpls.foo();
   }
}


通过使用Kotlin插件附带的字节码查看器(
Tools->Kotlin->Show Kotlin bytecode
,然后使用
Decompile
选项),您可以找到所有这些详细信息。

即使编译器以Java 8为目标,这是真的吗?在这种情况下,它是否将foo()定义为默认方法?许多关于OOP的书籍都写道,抽象方法是一种声明的方法,但不包含任何实现。谢谢你的解释!据我所知,Java8目标也使用了相同的内部类解决方案。使用内置反编译器和JD-GUI查看它。谢谢@zsmb13Thank you@hotkey
class MyClass: MyInterface {
    override fun bar() {
        println("MyClass")
    }
}
public final class MyClass implements MyInterface {
   public void bar() {
      System.out.println("MyClass");
   }
   public void foo() {
      MyInterface.DefaultImpls.foo();
   }
}