|
-
April 4th, 2011, 02:05 PM
#1
Use generics to operate on a class and its subclass equally
Hello,
I'm a bit new to Java (and OOP in general). I have a set of classes Vertex, Edge, and Graph that I'm trying to use to do some network analysis. These classes work fine.
I want to create a subclass of Vertex that I'm calling PrVertex, which is nearly identical to Vertex, except that it includes an extra parameter to describe that Vertex's probability. Methods that are used on PrVertex should work exactly the same as they would with Vertex, but PrVertex has one extra method to return the probability of that vertex.
A Graph is constructed of lists of Edges and Vertexes. I would like to be able to use a Graph object to represent either a list of Vertexes and a list of Edges OR a list of PrVertex-es and a list of Edges. The code using Graph objects simply uses them to pass between methods as a single object. After reading up on generics, I think this is possible, but I can't exactly wrap my mind around it.
The existing code that I'm using has a lot of statements like this:
Code:
ArrayList<Vertex> nodes = new ArrayList<Vertex>(graph.getVertexes());
where graph is a Graph instance.
I would like to be able to form a Graph with a list of PrVertex-es, and pass that to the existing code, agnostic of whether the Graph is PrVertex or Vertex. I tried to do this, but it would not compile, as the Graph constructor would not accept lists of type List<PrVertex>.
This is the code I'm utilizing, copied almost entirely from a tutorial by Lars Vogel
(http://www.vogella.de/articles/JavaA...a/article.html)
Code:
public class Vertex {
final private String id;
final private String name;
public Vertex(String id, String name) {
this.id = id;
this.name = name;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
}
Code:
public class PrVertex extends Vertex{
final private Double probability;
public PrVertex(String id, String name, Double probability){
super(id,name);
this.probability = probability;
}
public Double getProbability(){
return probability;
}
}
Code:
public class Graph {
private final List<Vertex> vertexes;
private final List<Edge> edges;
public Graph(List<Vertex> vertexes, List<Edge> edges) {
this.vertexes = vertexes;
this.edges = edges;
}
public List<Vertex> getVertexes() {
return vertexes;
}
public List<Edge> getEdges() {
return edges;
}
}
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|