问题
Suppose I am writing some classes to perform simple mathematical operations, and that I have an abstract class JNumber with a method in it for adding on another number:
public abstract class JNumber
{
public abstract JNumber add(JNumber addend);
// etc.
}
The return value from add represents the sum of this with the parameter addend.
Now suppose that I have an abstract subclass (called JFieldElement) of JNumber which includes a method for division (I cannot have this method in the JNumber class, because you can't divide integers, for example).
public abstract class JFieldElement
extends JNumber
{
public abstract JFieldElement div(JFieldElement divisor);
}
Now suppose I am writing a procedure that will take instances x,y,z of some class extending JFieldElement and compute an expression like:
x / (y + z)
I might try:
JNumber w = y.add(z);
JNumber result = x.div(w);
However, if do that then I get an error - since the return type of add is JNumber, we have to declare w as a JNumber. But then we cannot apply the function div to it, as that function needs to take in JFieldElement.
This would work if there was some way to specify that the add function should always return a value of the same type as whatever class it was called from. Is there a way of doing that?
回答1:
I think generics should do the trick here:
public abstract class JNumber<N extends JNumber<N>>
{
public abstract N add(N addend);
// etc.
}
回答2:
public <T extends JNumber> T add(T addend);
来源:https://stackoverflow.com/questions/22539945/is-there-any-way-to-specify-that-the-return-value-of-a-method-in-an-abstract-cla