简体   繁体   中英

Instantiate abstract class workaround

So since I will use various types of graphs I decided to put common behavior in abstract classes:

public abstract class Graph {

private List<Node> nodes;
private List<Edge> edges;

public void addNode(Node n) {
    nodes.add(n);
}

public void addEdge(Edge e) {
    edges.add(e);
}

public Node getNode(Node n) {
    return nodes.get(nodes.indexOf(n));
}

public Edge getEdge(Node left, Node right) {
    return edges.get(edges.indexOf(new Edge(left, right)));
   }
}

The getNode() does not complain (yet) even though the Node class is abstract. The problem is that the Edges are abstract too, but where the equals() and hashCode() has been overridden so that an edge can be identified by its nodes. It seems unnecessary to make the edge list protected or something else and implement the same getEdge() method in every subclass.

Is there a solution for this?

Simply don't make the Edge class abstract. If you have methods that you want implemented only in subclasses, make stub implementations in Edge that throw UnsupportedOperationException . In practice this causes very little actual problems because such errors in implementation are caught very early.

Another choice would be not to rely on List#indexOf but build your own custom algorithm that locates the edge based not on equals but on explicit comparison of the node pair. Basically it amounts to an implementation of equals semantics via an outside method (it could be a static method in Edge for convenience).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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