本文共 2122 字,大约阅读时间需要 7 分钟。
kotlin中既继承又实现
It may appear, we inherit more than one implementation of the same method.
看来,我们继承了同一方法的多个实现。
Need to implement all the methods which we have inherited from multiple interfaces.
需要实现我们从多个接口继承的所有方法。
package com.includehelp// declare interfaceinterface One{ // abstract function fun myName() // function with implementation fun sayHello(){ println("Hello, 'From Interface One' ") }}interface Two{ // function with implementation fun sayHello(){ println("Hello, 'From Interface Two' ") } // function with implementation fun myName(){ println("My Name is Interface 'Two'") }}// class implementing interfaceclass Three:One{ // override interface abstract method override fun myName() { println("My Name is Class Three") }}// class implementing more then one interfacesclass Four:One,Two{ // need to implement all the methods // which we have inherited from multiple interfaces override fun sayHello() { // Both interface have sayHello implementation in interfaces, // so explicitly define Interface name in super to call, // specific implementation from class super.sayHello() super .sayHello() println("Hello, From Class 'Four' ") } // need to implement all the methods // which we have inherited from multiple interfaces override fun myName() { // called super type implementation of method, // only interface two have implementation of this method, // so need to explicitly define interface name super.myName() println("My Name is Class Four") }}// Main function, Entry point of programfun main(){ // create class instance val four = Four() // call methods four.myName() // call methods four.sayHello()}
Output:
输出:
My Name is Interface 'Two'My Name is Class FourHello, 'From Interface One' Hello, 'From Interface Two' Hello, From Class 'Four'
翻译自:
kotlin中既继承又实现
转载地址:http://yjtzd.baihongyu.com/