如何在内部类中近似拥有静态变量?
我正在研究一系列类,它们都继承自单个基类、抽象类。
为了跟踪所有这些子类,我想实现类似 GUID 的东西 - 出于我的目的,它不必是实际的 GUID,只需一个对于每个实例都是唯一的 int 即可。儿童班。我一直希望使用递增的 int 。
我想做的是在我的抽象类中实现以下内容:
abstract class ParentObject{
static int GUID = 0;
//other stuff
}
此后每个子类在其构造函数中都会有 myGUID = GUID++;
但是,每当我尝试这样做时,我都会得到处理 IDE 出现以下错误:
字段 GUID 不能声明为静态;静态字段只能是 以静态或顶级类型声明。
由于处理处理类文件的方式(一切都是内部类),我不能拥有静态类成员。我可以选择哪些方式以其他方式复制此功能?
编辑:这是在Processing 和Processing IDE 中完成的。 ParentObject 类位于其自己的处理文件中。
Edite2:我了解到Processing与Java不同的原因是所有Processing类都是内部类。因此,我重新添加了 Java 标签并重新表述了问题。
I am working on a series of classes that all inherit from a single, base, abstract class.
In order to keep track of all of these child classes, I'd like to implement something like a GUID -- for my purposes, it doesn't have to be an actual GUID, just an int that is unique to each instance of a child class. An incremented int is what I'd been hoping to use.
What I'd have liked to do, is implement the following in my abstract class:
abstract class ParentObject{
static int GUID = 0;
//other stuff
}
whereafter each child class, in its constructor, would have myGUID = GUID++;
However, whenever I try this, I get the following error from the Processing IDE:
The field GUID cannot be declared static; static fields can only be
declared in static or top-level types.
Because of how Processing handles class files (everything is an inner class), I can't have static class members. What are my options to duplicate this functionality in other ways?
Edit: This is being done in Processing and the Processing IDE. The ParentObject class is in its own processing file.
Edite2: I have learned that the reason Processing is different from Java is that all Processing classes are Inner Classes. Because of this, I have re-added the Java tag and reformulated the question.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好吧,那就面对吧。你做不到。如果您确实需要它,请声明一个外部类来处理这段代码,并在顶级类的构造函数中调用它。
如果您必须使用内部类的这种层次结构,那么您就不能这样做。 Java 不会以你不想要的方式接受它。您可以将抽象类声明为静态。
但我几乎可以肯定这对你也不起作用。因此,我建议在其他地方创建一个新的外部类来处理它。
这可能会降低您的应用程序的速度(取决于您实例化类的频率),但不会有很大影响。
Well, then face it. You can't do it. If you REALLY need it, declare an outer class for handling this piece of code, and call it in the top-level class's constructor.
If you MUST use this hierarchy of innerclass, then you can't do it. Java won't accept it in the way you wan't. You could declare your abstract class as static.
But I'm almost sure this won't work for you either. So, I suggest to create a new outer class somewhere else to handle it.
This may speed down your app (depending on how often you instantiate a class), but not in a significant way.
静态受保护方法 getNextGUID() 可以工作,
当你有多个线程时,不要忘记同步它/使用 AtomicInteger
a static protected method getNextGUID() would work
don't forget to synchronize it/use AtomicInteger when you have multiple threads