查询Java中的接口

前端之家收集整理的这篇文章主要介绍了查询Java中的接口前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
说我有两个接口A和接口B:
public interface A {
  public int data();
}

public interface B {
  public char data();
}

接口A有一个方法public int data()和接口B有一个方法public char data().

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

解决方法

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()),因此编译器不能区分两者,并且将具有满足两个接口契约的单一方法.

编辑:

例如,

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!
原文链接:https://www.f2er.com/java/120845.html

猜你在找的Java相关文章