0

I am trying to create a generic class in which the generic type itself can have methods.

This is what I did in Java:

public class DepthFirstPaths <GraphType> implements PathInterface
{
    private final int start;        

    public DepthFirstPaths (GraphType G, int s)
    {
        int vCount = G.numVertex(); //This line is giving errors
        start = s;

        DFS(G, s);
    }

    //Other methods
    ....
}

GraphType can refer to a directed graph type or undirected graph type and this is because DFS does the same thing for both types of graphs given a source vertex. But the above java code gives errors like:

Description: The method numVertex() is undefined for the type GraphType
Resource: DepthFirstPaths.java
Path: /Paths/src/GraphAlgorithms
Location: line 17
Type: Java Problem

Plus other errors relating to using GraphType object methods in the code

What can I do to fix this? What is the best way to do this?

1
  • I guess you are porting some C++ code to java... Commented Nov 15, 2013 at 22:09

1 Answer 1

4

This definition

public class DepthFirstPaths <GraphType>

Means your generic type name is GraphType.

To make your class always work with a GraphType, you should mark your generic extends from GraphType:

public class DepthFirstPaths <T extends GraphType>

Then just use T in your code to refer to the generic:

public class DepthFirstPaths <T extends GraphType> implements PathInterface {
    private final int start;        

    public DepthFirstPaths (T G, int s) {
        //This line won't give you errors anymore
        //except if GraphType doesn't have a numVertex method
        int vCount = G.numVertex();
        start = s;

        DFS(G, s);
    }

    //Other methods
    ....
}
Sign up to request clarification or add additional context in comments.

4 Comments

So say I have the 2 graph classes: undirGraph and dirGraph, do I have to write: public class DepthFirstPaths <T extends undirGraph, dirGraph>?
If UndirGraph and DirGraph classes extend from GraphType, you won't need to do that.
Aha, I see. So I have to somehow make all Graph objects extend GraphType then I can use your above syntax? So what should GraphType be? interface? Abstract class?
That will depend on your design but IMO it should be an interface. You can define such design based on the List interface and ArrayList class implementation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.