从抽象类继承静态变量 [英] Inheriting static variable from abstract class

查看:25
本文介绍了从抽象类继承静态变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有六个类,它们都扩展了同一个抽象类.抽象类有一个指向一些 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 的抽象类 bar 和一个打印 foo 内容的 printFoo 方法.然后我依次实例化 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.

类似的东西

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆