从抽象类继承静态变量
我有六个类,它们都扩展了同一个抽象类。抽象类有一个静态变量,指向一些 JNI 代码,我只想在每次类实例化时加载一次。
据我了解,这会导致该静态变量的一个实例被实例化,但我想要的是每个扩展类都有自己的静态变量实例,该实例对于给定的子类是唯一的。我想在我的抽象类中编写一些代码来修改和/或释放抽象类。是否可以同时做这两件事?
作为一个例子,我可以编写一个带有变量 foo 的抽象类 bar 和打印 foo 内容的 printFoo 方法。然后我按顺序实例化 fooBar1、fooBar2 和 fooBar3,它们各自扩展 bar 类并将 foo 初始化为静态块中的不同值。如果我调用 foobar1.printFoo 我想打印由 fooBar1 构造函数初始化的 foo 的静态值。
这可以在java中完成吗?
I have half a dozen classes which all extend the same abstract class. The abstract class has a static variable pointing to some JNI code that I only want to load once per instantiation of the classes.
From what I understand this results in exactly one instance of this static variable being instantiated, but what I want is for each of the extending classes to have their own static instance of the variable that is unique for the given child class. I want to write some code in my abstract class that modifies and/or releases the abstract class. Is it possible to do both of these things at once?
So as an example can I write an abstract class bar with an variable foo and a printFoo method which prints the content of foo. Then I instantiate in order fooBar1, fooBar2, and fooBar3 which each extend the bar class and initialize foo to different values in static blocks. If I call foobar1.printFoo
I want to print the static value of foo initialized by fooBar1 constructor.
Can this be done in java?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以近似它,但每个子类都需要单独的静态变量,以阻止子类覆盖彼此的值。最简单的方法是通过 getter getFoo 来抽象它,以便每个子类从正确的位置获取 foo。
像这样的东西
You can approximate it, but you will need separate static variables for each subclass, to stop subclasses overwriting each others values. It's easiest to abstract this via a getter
getFoo
so that each subclass fetches the foo from the right place.Something like this
我有类似的问题。看来Java不能隔离静态成员(属性)。我最终添加了一个抽象方法而不是属性:
I have a similar problem. Looks like Java can't isolate static members (attributes). I ended up adding an abstract method instead of the attribute: