12

I am tempted to do such kind of code, using jGraphT

/*
  interface DirectedGraph<V,E> { ...}
  interface WeightedGraph<V,E> { ...}
*/

public class SteinerTreeCalc  {

    public SteinerTreeCalc( < ??? implements DirectedGraph<V,E>, WeightedGraph<V,E> > graph )  {
     ......
    }


}

I want to create a constructor that ask for an object implementing two interfaces.

Update :

In my goal, there are already chosen classes for Vertex and Edges (V and E), but thanks a lot to people who come up with :

public class SteinerTreeCalc <V, E, T extends DirectedGraph<V, E> & WeightedGraph<V, E>>  
{ 
   ....
}
jwinandy
  • 1,739
  • 12
  • 22
  • I assume you have a good reason for not naming the interface that is both a `DirectedGraph` and a `WeightedGraph`, so that you can get all the bits of the contract that the user of the `SteinerTreeCalc` is required to support in one place? – Donal Fellows Sep 16 '10 at 09:40
  • A good one ! JgraphT doesn't provide such interface that is both a DirectedGraph and a WeightedGraph, and the user might not want to use my custom interface/classes. I don't really understand why they didn't provide this interface. – jwinandy Sep 16 '10 at 10:24

5 Answers5

21

Yes, it's possible:

public class SteinerTreeCalc<T extends DirectedGraph<V,E> & WeightedGraph<V,E>> {
  public SteinerTreeCalc(T graph) {
    ......
  }
}
amorfis
  • 15,390
  • 15
  • 77
  • 125
9

Should work like this, but this is complexer generics logic, hope you can adapt:

public static interface DirectedGraph<V, E> {
}

public static interface WeightedGraph<V, E> {
}

public <V, E, T extends DirectedGraph<V, E> & WeightedGraph<V, E>> SteinerTreeCalc(T bothInterfaces) {
    // do it
}

These are the interfaces and the constructor like asked in your question.

GHad
  • 9,611
  • 6
  • 34
  • 40
  • +1: Very similar to what I was coding. However, wouldn't `V` and `E` reside on the class itself and not on the constructor? I suppose it depends on the author's goals. – Adam Paynter Sep 16 '10 at 09:05
6

This could be what you want:
Hidden Features of Java

Community
  • 1
  • 1
Enno Shioji
  • 26,542
  • 13
  • 70
  • 109
2

you can use extends instead of implements in above code

jmj
  • 237,923
  • 42
  • 401
  • 438
0

If V and E are concrete classes rather than type parameters, then you could create a new interface as follows:

public interface DirectedWeightedGraph extends 
    DirectedGraph<V,E>, WeightedGraph<V,E> {
}

then

public class SteinerTreeCalc  {

    public SteinerTreeCalc(DirectedWeightedGraph graph)  {
       ...
    }
}

The problem is that the actual argument must implement the DirectedWeightedGraph interface. A type that just implements DirectedGraph<V,E> and WeightedGraph<V,E> is not sufficient.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216