Kotlin interface
Kotlin
interface is similar to Java 8, using the interface
keyword defines the interface, allowing the method to have a default implementation:
interfaceMyInterface{funbar()//unrealizedfunfoo(){//
Implemented//Optional method bodyprintln("foo")}}
Implementation interface
A class or object can implement one or more interfaces.
classChild:MyInterface{overridefunbar(){//Method Body}}
Example
interfaceMyInterface{funbar()funfoo(){//Optional Method Body println("foo")}}classChild:
MyInterface{overridefunbar(){//Method Bodyprintln("bar")}}funmain(args:Array<String>){valc=Child()c.foo();c.bar();}
The output is as follows:
foo
bar
Properties in the interface
The properties in the interface can only be abstract, initialization values are not allowed, and the interface does not hold property values. When implementing the interface, you must override the properties:
interfaceMyInterface{varname:String//name attribute,
abstract}classMyImpl:MyInterface{overridevarname:String="runoob"//Overridden properties}
Example
interfaceMyInterface{varname:String//name attribute,
abstractfunbar()funfoo(){//Optional Method Bodyprintln("foo")}}classChild:MyInterface{overridevarname:
String="runoob"//Overridden properties overridefunbar(){//Method Body println("bar")}}funmain(args:
Array<String>){valc=Child()c.foo();c.bar();println(c.name)}
The output is as follows:
foo
bar
runoob
Function rewriting
When implementing multiple interfaces, you may encounter the problem that the same method inherits multiple implementations. For example:
Example
interfaceA{funfoo(){print("A")}//Realized funbar()//unrealized,There is no method body, it is abstract}interfaceB{funfoo(){print("B")}//Realized funbar()
{print("bar")}//Realized}classC:A{overridefunbar(){print
("bar")}//rewrite}classD:A,B{overridefunfoo(){super<A>.foo()
super<B>.foo()}overridefunbar(){super<B>.bar()}}funmain(args:
Array<String>){vald=D()d.foo();d.bar();}
The output is as follows:
ABbar
Both interfaces A and B define methods in the example foo()
and bar()
both have been realized foo()
B realized bar()
. BecauseC is a concrete class that implements A, it must be overridden bar()
and implement this abstract method.
However, if we derive D from An and B, we need to implement all the methods inherited by multiple interfaces and indicate how D should implement them. This rule applies to inheriting a single implementation ( bar()
) can also be used to inherit multiple implementations ( foo()
).