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?

我只是一个虾纸丫 提交于 2019-12-25 07:47:42

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!