简体   繁体   English

Java - 使用Object参数实现接口

[英]Java - Implementing interface with Object argument

I was implementing a Java Graph library (to learn ...). 我正在实现一个Java Graph库(要学习......)。 Accordingly, I wrote an interface 因此,我写了一个界面

public interface DigraphInterface {
    public boolean isEmpty();
    public int size();
    public boolean isAdjacent(Object v, Object w);
    public void insertEdge(Object v, Object w);
    public void insertVertex(Object v);
    public void eraseEdge(Object o, Object w);
    public void eraseVertex(Object v);
    public void printDetails();
}

As the first step towards implementing, I am writing Digraph class that implements above interface. 作为实现的第一步,我正在编写实现上述接口的Digraph类。 However, to keep things simple, I want the node identifiers as integers, so I defined functions as 但是,为了简单起见,我希望节点标识符为整数,因此我将函数定义为

    @Override
    public boolean isAdjacent(int v, int w) {
            // TODO Auto-generated method stub
            return adjList[v].contains(w) || adjList[w].contains(v);
    }  

But, I am getting error, that I need to override or implement method with supertype. 但是,我收到错误,我需要覆盖或实现超类型的方法。 Can someone explain me the underpinnings for this behavior. 有人可以解释我这种行为的基础。 Also, if someone can explain, how do we design libraries that allow flexibility to add components of any type. 此外,如果有人可以解释,我们如何设计允许灵活添加任何类型组件的库。

You interface says: 你的界面说:

public boolean isAdjacent(Object v, Object w);

you implement: 你实现:

public boolean isAdjacent(int v, int w)

for java this hasn't the same signature, therefore isn't the same method. 对于java这个签名不一样,因此方法不一样。 What you could do is to use generics, it depends on what you need but, in this case you could do something like: 你可以做的是使用泛型,这取决于你需要什么,但在这种情况下,你可以做类似的事情:

public interface DigraphInterface<T> {
    ...
    public boolean isAdjacent(T v, T w);
    ...
}

and your implementation could be: 你的实施可能是:

public class DefaultDigraph<Integer> {
    ...
    public boolean isAdjacent(Integer v, Integer w) {
        ...
    }
    ...
}

of course you need to take care, because Integer can be null, and int not. 当然你需要小心,因为Integer可以为null,而int不是。 Therefore null checks over parameters would be a good idea, before its auto-unboxing. 因此,在自动取消装箱之前,对参数进行空检查是个好主意。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM