Inheriting static variable from abstract class

后端 未结 2 452
悲哀的现实
悲哀的现实 2020-12-17 17:07

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 in

相关标签:
2条回答
  • 2020-12-17 17:24

    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:

    public abstract class Abs {
        public void printX() {
            System.out.println("For " + this.getClass() + " x=" + getX());
        }
    
        protected abstract Integer getX();
    
    }
    
    public class A extends Abs {
        protected static Integer x = 1;
    
        @Override
        protected Integer getX() {
            return x;
        }
    
    }
    
    public class B extends Abs {
        protected static Integer x = 2;
    
        @Override
        protected Integer getX() {
            return x;
        }
    
    }
    
    public class test {
    
        public static void main(String args[]) {
            Abs a = new A();
            a.printX();
            Abs b = new B();
            b.printX();
            Abs c = new A();
            a.printX();
            b.printX();
            c.printX();
    
        }
    }
    
    0 讨论(0)
  • 2020-12-17 17:28

    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

    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";
       }
    }
    
    0 讨论(0)
提交回复
热议问题