gpt4 book ai didi

java - 查询Java中的接口(interface)

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:14:26 26 4
gpt4 key购买 nike

假设我有两个接口(interface)接口(interface) A 和接口(interface) B:

public interface A {
public int data();
}

public interface B {
public char data();
}

接口(interface) A 有一个方法 public int data(),接口(interface) B 有一个方法 public char data()

当我在某些类 C 中同时实现接口(interface) A 和 B 时,编译器会给我一个错误。这是java的缺陷吗?我认为这是不允许我们扩展多个类的主要原因之一,那么当这个问题仍然存在时为什么允许我们实现多个接口(interface)?

最佳答案

The Java Tutorials: Defining Methods - Overloading Methods州,

The Java programming language supports overloading methods, and Java can distinguish between methods with different method signatures. This means that methods within a class can have the same name if they have different parameter lists.

还有,

You cannot declare more than one method with the same name and the same number and type of arguments, because the compiler cannot tell them apart.

The compiler does not consider return type when differentiating methods, so you cannot declare two methods with the same signature even if they have a different return type.

这两个实现的方法共享一个共同的方法签名(即data()),因此,编译器无法区分这两者,只会让那个方法满足两个接口(interface)契约(Contract)。


编辑:

例如,

public class Foo implements IFoo, IBar{

public static void main(String[] args) {
Foo foo = new Foo();
((IFoo) foo).print();
((IBar) foo).print();
}

@Override
public void print() {
System.out.println("Hello, World!");
}
}

public interface IBar {
void print();
}

public interface IFoo {
void print();
}

这将输出,

Hello, World! 
Hello, World!

关于java - 查询Java中的接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11172179/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com