Querying interfaces in Java

Say I have two interfaces a and B:

public interface A {
  public int data();
}

public interface B {
  public char data();
}

Interface a has a method public int data() and interface B has a method public char data()

When I implemented interfaces a and B in some classes C, the compiler gave me an error Is this a defect in Java? Because I think this is one of the main reasons why we are not allowed to extend multiple classes, so why are we allowed to implement multiple interfaces when this problem still exists?

Solution

The Java tutorials: defining methods – overloading methods,

Also,

The two implemented methods share a common method signature (i.e. data ()), so the compiler cannot distinguish between the two, and will have a single method that satisfies the two interface contracts

Edit:

For example,

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();
}

Will output,

Hello,World! 
Hello,World!
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>