这是简短的版本。首先也是最重要的:我希望我的类是不可变的。我知道一个类不能既是抽象的又是最终的。 我要问的是:有没有办法只允许内部类扩展和实现外部抽象类?这可能不是实现我的最佳方法不可变的目标,所以如果有人有更好的设计,我很想听听。
我正在为 vector 运算编写一个类——就像在物理和工程中一样,而不是在编程方面。 (我也知道 JScience has a package 用于这类东西。我想自己写,并保持简单。)
我喜欢 Java 几何包中使用的模式,例如,可以使用以下两种精度级别之一创建 Line2D
:float 或 double。
public abstract class Line2D {
public static class Float extends Line2D { /* Implementation */ }
public static class Double extends Line2D { /* Implementation */ }
}
这是我非常想在类里面加入和扩展的功能,因此我创建了以下功能:
public abstract class Vector2D {
public final static class Integer extends Vector2D {
// Component length projected along x/y axis, respectively
final private int i, j;
public Integer( int i, int j ) {
this.i = i;
this.j = j;
}
public Object doStuff() { /* vector operations */ }
}
public final static class Float extends Vector2D {
// Identical to Vector2D.Integer, except with floats
}
public final static class Double extends Vector2D { /* Same Idea */ }
// Outer class methods and whatnot
}
显然,Vector2D.Integer
、Vector2D.Float
和 Vector2D.Double
都是最终的。除了这些内部类之外,有什么方法可以使 Vector2D
最终成为所有内容?
最佳答案
Is there a way to only allow inner classes to extend and implement the outer, abstract class?
是的,将外部类的构造函数设为私有(private)。
示例:
abstract class MyAbstractClass {
int i; // some property
private MyAbstractClass(int i) {
this.i = i;
}
public static class InnerConcrete extends MyAbstractClass {
int j; // some other property
public InnerConcrete(int i, int j) {
super(i);
this.j = j;
}
}
}
我想我从来没有遇到过这种方法。工厂模式可能更灵活,并允许您将原本可能很大的类拆分为多个文件。抽象类的包访问级别可能也足够了。
关于java - 如何创建一个抽象的、不可变的类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27911801/