简体   繁体   中英

Is there any way to specify that the return value of a method in an abstract class should be of the same type as the containing class?

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?

public <T extends JNumber> T add(T addend);

I think generics should do the trick here:

public abstract class JNumber<N extends JNumber<N>>
{
  public abstract N add(N addend);
  // etc.
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM