为什么我不能在Java

时间:2018-01-21 01:30:51

标签: java

我的vertex interface包含element

public interface Vertex<V> {
    public V element()throws InvalidEdgeException;
}

implementation

interface vertices的{​​{1}}
class MyVertices

我的疑问是,当我尝试测试方法时public class MyVertex<V,E> implements Vertex<V> { private V elem; private Graph<V, E> myGraph; public MyVertex(V elem) { this.elem = elem; this.myGraph = new GraphLinked<>(); } @Override public V element() throws InvalidVertexException { if (elem == null) { throw new InvalidVertexException("vertex null"); } return elem; } private MyVertex checkVertex(Vertex<V> p) throws InvalidVertexException { if (p == null) { throw new InvalidVertexException("checkVertex = NULL"); } try { return (MyVertex) p; } catch (ClassCastException e) { throw new InvalidVertexException("WRONG vertex"); } } } 返回checkVertex(Vertex<V> p),因为throw new InvalidVertexException("WRONG vertex")不能cast

MyVertex

制作接口的实现,当然应该做一个转换,因为它实现了它的接口

任何建议?

1 个答案:

答案 0 :(得分:1)

删除虚拟try-catch ClassCastException,您将知道投射失败的原因。