Oop 重写来自不同接口的相同签名
在C sharp中,如果我们有两个接口,使用相同的签名方法,我们可以在一个类中实现它们,方法如下:Oop 重写来自不同接口的相同签名,oop,interface,kotlin,Oop,Interface,Kotlin,在C sharp中,如果我们有两个接口,使用相同的签名方法,我们可以在一个类中实现它们,方法如下: interface A { void doStuff(); } interface B { void doStuff(); } class Test : A, B { void A.doStuff() { Console.WriteLine("A"); } void B.doStuff() { Console.WriteLine("A"); } } 如果我们把这件事告诉科特林 inte
interface A
{
void doStuff();
}
interface B
{
void doStuff();
}
class Test : A, B
{
void A.doStuff()
{
Console.WriteLine("A");
}
void B.doStuff()
{
Console.WriteLine("A");
}
}
如果我们把这件事告诉科特林
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"
}
接口A
{
fundostuff()
}
接口B
{
fundostuff()
}
班级考试:A、B
{
覆盖fun doStuff(){
println(“A b相同”)
}
}
趣味主线(args:Array)
{
var test=test();
test.doStuff()//将为“b”打印相同的内容
变量A:A=测试
var接口B:B=测试
InterfaceA.doStuff()//将为A b打印相同的内容”
InterfaceB.doStuff()//将为“b”打印相同的内容
}
所以,我的问题是,我怎样才能
为每个接口提供一个不同的实现,如C sharp示例中所示?。
**注:我已经阅读了上的文档,有一个类似的示例
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()
}
}
接口A{
fun foo(){print(“A”)}
}
接口B{
fun foo(){print(“B”)}
}
D类:A、B{
覆盖fun foo(){
super.foo()
super.foo()
}
}
在这里,foo在每个接口中实现,因此在D中实现时,它只调用接口中定义的实现。但是我们如何在D中定义不同的实现?在Kotlin中不可能。Kotlin在这方面与Java类似。在接口中重写等效的方法必须具有相同的实现该行为背后的基本原理是,将对象引用转换为不同类型不应改变其方法的行为,例如:
val test = Test()
(test as A).doStuff()
(test as B).doStuff() // should do the same as above
请重新格式化您的示例代码格式(添加缩进)现在@voddan是否更好?尽管它不代表扩展函数:P