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,719
  • 12
  • 21
  • 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
  • 14,710
  • 15
  • 71
  • 118
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,571
  • 6
  • 33
  • 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
  • 25,972
  • 13
  • 68
  • 108
2

you can use extends instead of implements in above code

jmj
  • 232,312
  • 42
  • 391
  • 431
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
  • 669,072
  • 92
  • 771
  • 1,162