关于无法包含静态抽象 Java 方法存在许多问题。还有很多关于此问题的解决方法(设计缺陷/设计强度)。但我找不到任何针对我将很快说明的具体问题的信息。
在我看来,创建 Java 的人以及相当多使用 Java 的人并不像我和其他许多人那样将静态方法视为类函数或属于该类的方法并且不针对任何对象。那么还有其他方法来实现类函数吗?
这是我的例子:在数学中,group是一组可以使用某种操作*以某种合理的方式彼此组合的对象 - 例如,正实数在正常乘法下形成一个群(x * y = x × y),并且整数集形成一个群,其中“乘法”运算是加法(m * n = m + n).
在 Java 中对此进行建模的一种自然方法是为组定义一个接口(或抽象类):
public interface GroupElement
{
/**
/* Composes with a new group element.
/* @param elementToComposeWith - the new group element to compose with.
/* @return The composition of the two elements.
*/
public GroupElement compose(GroupElement elementToComposeWith)
}
我们可以为上面给出的两个例子实现这个接口:
public class PosReal implements GroupElement
{
private double value;
// getter and setter for this field
public PosReal(double value)
{
setValue(value);
}
@Override
public PosReal compose(PosReal multiplier)
{
return new PosReal(value * multiplier.getValue());
}
}
and
public class GInteger implements GroupElement
{
private int value;
// getter and setter for this field
public GInteger(double value)
{
setValue(value);
}
@Override
public GInteger compose(GInteger addend)
{
return new GInteger(value + addend.getValue());
}
}
然而,群体还有另一个重要的属性:每个群体都有一个单位元- 一个元素e这样x * e = x对全部x在组中。例如,乘法下正实数的单位元是1,加法下整数的单位元是0。在这种情况下,为每个实现类提供一个方法是有意义的,如下所示:
public PosReal getIdentity()
{
return new PosReal(1);
}
public GInteger getIdentity()
{
return new GInteger(0);
}
但这里我们遇到了问题——方法getIdentity
不依赖于对象的任何实例,因此应该声明static
(事实上,我们可能希望从静态上下文中引用它)。但如果我们把getIdentity
方法进入接口然后我们不能声明它static
在界面中,所以不能static
在任何实现类中。
有什么方法可以实现这个getIdentity
方法:
- 强制所有实现的一致性
GroupElement
,这样每次执行GroupElement
被迫包括一个getIdentity
功能。
- 表现静态;即,我们可以获得给定实现的恒等元素
GroupElement
无需实例化该实现的对象。
条件(1)本质上是说“是抽象的”,条件(2)是说“是静态的”,我知道static
and abstract
在 Java 中不兼容。那么语言中有一些相关的概念可以用来做到这一点吗?