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

标签 java interface object-oriented-analysis overriding

假设我有两个接口(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/

相关文章:

java - SQLite 及其驱动程序

java - 购物车的OO设计模式

c++ - 在这种情况下,哪种设计模式可以很好地实现运行时多态性?

java - Android - 从 url 下载 JSON 文件

java - 如何在android中为多个线程使用多个按钮?

unit-testing - 我可以使用嵌套界面模拟库代码吗?

java - 'model' 和 'view' 之间的接口(interface)

c# - 面向对象设计 : using method parameters vs properties

java - Spring 安全。删除一个拦截 URL 后不重定向到登录页面

java - Java中如何获取返回类型为List接口(interface)的对象?