覆盖来自不同接口的相同签名

时间:2017-05-20 05:44:28

标签: oop interface kotlin

在c sharp中,如果我们有2个接口,使用相同的签名方法,我们可以通过以下方式在一个类中实现它们:

interface A 
{
 void doStuff();
}
interface B
{
 void doStuff();
}
class Test : A, B
{
void A.doStuff()
{
 Console.WriteLine("A");
}
void B.doStuff()
{
 Console.WriteLine("A");
}
}

如果我们将其翻译成Kotlin,我们有

interface  A
{
 fun doStuff()
} 
interface  B
{
 fun doStuff()
}
class Test : A, B
{
  override fun doStuff() {
            println("Same for A b")
                         }
}
fun main(args: Array<String>)
{
  var test = Test();
  test.doStuff() //will print Same for A b"
  var InterfaceA:A = test
  var InterfaceB:B = test
  InterfaceA.doStuff()//will print Same for A b"
  InterfaceB.doStuff()//will print Same for A b"
}

所以,我的问题是,¿我怎么能  给每个接口一个不同的实现,如简洁的例子? **注意:我已阅读https://kotlinlang.org/docs/reference/interfaces.html上的文档,有一个类似的例子,

interface A {
 fun foo() { print("A") }
}
interface B {
 fun foo() { print("B") }
}
class D : A, B {
 override fun foo() {
  super<A>.foo()
  super<B>.foo()
     }
}

这里,foo在每个接口中实现,因此当在D中实现时,它只调用接口中定义的实现。但是¿我们如何在D?中定义不同的实现?

1 个答案:

答案 0 :(得分:1)

Kotlin不可能。在这方面,Kotlin类似于Java。接口中覆盖等效的方法必须在类中具有相同的实现。该行为背后的基本原理是,对不同类型的对象引用不应改变其方法的行为,例如:

val test = Test()
(test as A).doStuff()
(test as B).doStuff() // should do the same as above
相关问题