从抽象类继承静态变量 [英] Inheriting static variable from abstract class
问题描述
我有六个类,它们都扩展了相同的抽象类。抽象类有一个静态变量,指向一些JNI代码,我只想在每个类的实例化时加载一次。
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?
因此,我可以编写一个带有变量foo的抽象类栏和一个打印内容的printFoo方法foo。然后我按顺序实例化fooBar1,fooBar2和fooBar3,每个扩展bar类并将foo初始化为静态块中的不同值。如果我调用 foobar1.printFoo
我想打印由fooBar1构造函数初始化的foo的静态值。
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.
这可以可以在java中完成吗?
Can this be done in java?
推荐答案
你可以近似它,但是每个子类需要单独的静态变量,以阻止子类覆盖彼此的价值观。最简单的方法是通过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像这样
Something like this
abstract class Bar
{
// you don't have to have this in the base class
// - you could leave out the variable and make
// getFoo() abstract.
static private String foo;
String getFoo() {
return foo;
}
public void printFoo() {
System.out.print(getFoo());
}
}
class Foo1 extends Bar
{
static final String foo1;
public String getFoo() {
return foo1; // return our foo1 value
}
public Foo1() {
foo1 = "myfoo1";
}
}
class Foo2 extends Foo1
{
static final String foo2;
public String getFoo() {
return foo2; // return our foo2 value
}
public Foo2() {
foo2 = "myfoo2";
}
}
这篇关于从抽象类继承静态变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!