Reputation: 7670
I have the following interfaces
public interface Group {
public Group add(Group g);
public Group sub(Group g);
public Group getAddInv();
public boolean isZero();
}
public interface Ring extends Group {
public Ring mul(Ring r);
public boolean isOne();
}
I now want to make these interfaces generic to make sure the methods can only be called for elements of the same algebraic structure.
For example it should be possible to add two elements of Ring but not to add one Element of Group and one element of Ring.
My first thought was using < ? super Ring > for the methods of Group, but that didn't work out. How can i achieve this?
Update:
public interface Group<T> {
public T add(T g);
public T sub(T g);
public T getAddInv();
public boolean isZero();
}
public interface Ring<T> extends Group<Ring<T>> {
public T mul(T r);
public boolean isOne();
}
Would that be a solution?
Upvotes: 2
Views: 233
Reputation: 122538
It should be like this:
public interface Group<T> {
public T add(T g);
public T sub(T g);
public T getAddInv();
public boolean isZero();
}
public interface Ring<T> extends Group<T> {
public T mul(T r);
public boolean isOne();
}
Actual implementations would implement these interfaces with a type parameter of themselves:
class MyInteger implements Ring<MyInteger>
Upvotes: 4
Reputation: 2295
I would not try to do this via the type system. First, as some comments already mentioned, the interface seems rather odd (what does adding one group to another mean?). Instead I'd focus on what is usually done on a group, which would like this
interface Group<T>{
T add(T e1, T e2); //adds two elements of the group and returns the result
//sub is not a group operation, there is normally only one op
...
}
The same for the Ring, but add the mul()
operation.
If you want to enforce that only elements that are contained within the group/ring can be used in operations, you implementation should check if the args are in the group/ring and throw an exception if not. The the type system is not designed to do this, as this is a value based check, not a type check.
Upvotes: 1
Reputation: 3893
Maybe do you want to use such an interface:
public interface Test<T> {
public void add(T t);
}
And then if you want you can use instanceof in you functions ?
Upvotes: 1