【发布时间】:2014-06-17 04:19:35
【问题描述】:
我有一个公共单元课程。我只想通过 Unit 类访问 GeofenceUnit 类。因此,我将 GeofenceUnit 设为 Unit 的内部类。一个单元有许多地理围栏单元。因此,当我实例化一个 Unit 时,我想在 Unit 对象中存储许多 GeofenceUnit。
public class Unit {
public ArrayList<Unit.GeofenceUnit> geofences;
public Unit(int id){
this.id = id;
geofences = this.geofence.fill();
}
private static class GeofenceUnit {
ArrayList<GeofenceUnit> geofences;
private static ArrayList<Unit.GeofenceUnit> fill(){
...
while(resultSet.next()){
geofences.add(new Geofence());
}
return geofences;
}
}
}
您可能已经注意到,上述代码的问题是我试图在 Unit 的构造函数中调用静态方法 fill()。这会产生警告“应以静态方式访问 Unit.GeofenceUnit 类型的静态方法 fill()”。我完全同意这个警告。我不想通过静态方式访问它。但是,如果我从 GeofenceUnit 类定义及其 fill() 方法签名中删除静态修饰符,那么它在逻辑上没有意义。为什么我要在一个实例方法中填充许多 GeofenceUnits。良好的程序实践表明方法应该是静态的。
我想我这里的设计很糟糕。关于如何重构它的任何建议?
【问题讨论】:
-
只是一个提示,如果您正在寻找有关工作代码的建议,CodeReview SE 将是一个不错的发帖地点
-
为什么不直接叫它
GeofenceUnit.fill()? -
if I remove the static modifiers from the GeofenceUnit class definition and its fill() method signature。确保您了解拥有static嵌套类的含义。 -
@JonSkeet 我不知道您可以通过这种方式访问内部类。我以为你只能通过这个关键字访问内部类。
-
这会带来其他问题,因为我确实需要从内部类访问外部类的成员变量,而静态内部类无法做到这一点。
标签: java static inner-classes