Static member variable conundrum

I'm using an abstract base class so that subclasses can share common functionality.
Each subclass needs a static member variable (a String) that needs to be accessed from the abstract base class in some of it's methods.
This is where the problem is; I would like to declare an abstract variable in the base class so that the base class methods can use the variable, but you can't make an abstract variable static.
Is there a way around this or am I approaching this problem from the wrong direction?

I can't remember if you can override static methodsTested this and determined that you can't. The superclass static gets called. Makes sense.
I also tested my suggested code, and made a few improvements ... maybe it isn't quite so ugly after all (can you tell that I'm slogging through some boring stuff?):
public class Tester1
    protected static HashMap _stringTable = new HashMap();
    static
        _stringTable.put(Tester1.class, "Tester 1");
    protected String getString()
        return (String)_stringTable.get(this.getClass());
    public static void main(String[] argv)
        Tester1 t1 = new Tester1();
        Tester2 t2 = new Tester2();
        Tester1 t3 = new Tester2();
        System.out.println("t1.getString() = " + t1.getString());
        System.out.println("t2.getString() = " + t2.getString());
        System.out.println("t3.getString() = " + t3.getString());
public class Tester2 extends Tester1
    static
        _stringTable.put(Tester2.class, "Tester 2");

Similar Messages

  • Problems with static member variables WAS: Why is the static initializer instantiating my class?!

    Hi,
    I have been hunting down a NullPointerException for half a day to come to
    the following conclusion.
    My constructor calls a method which uses static variables. Since an intance
    of my class is created in the static block when the class is loaded, those
    statics are probably not fully initialized yet and the constructor called
    from the static block has those null pointer problems.
    I've considered moving the initialization of the static variables from the
    declaration to the static block. But your code is inserted BEFORE any other
    code. Therefore not solving my problem.
    Two questions:
    1) what would be a solution to my problem? How can I make sure my static
    variables are initialized before the enhancer generated code in the static
    block calls my constructor? Short of decompiling, changing the code and
    recompiling.
    2) Why is the enhancing code inserted at the beginning of the static block
    and not at the end? The enhancements would be more transparent that way if
    the static variables are initialized in the static block.
    Thanks,
    Eric

    Hi Eric,
    JDO calls the no-args constructor. Your application should regard this constructor as belonging
    primarily to JDO. For example, you would not want to initialize persistent fields to nondefault
    values since that effort is wasted by JDO's later initilization to persistent values. Typically all
    you want to initialize in the no-args constructor are the transactional and unmanaged fields. This
    rule means that you need initialization after construction if your application uses the no-args
    constructor and wants persistent fields initialized. On the other hand, if your application really
    uses constructors with arguments, and you're initializing persistent fields in the no-args
    constructor either unintentionally through field initializers or intentionally as a matter of
    consistency, you will find treating the no-args constructor differently helpful.
    On the other hand, if Kodo puts its static initializer code first as you report, then it is a bug.
    Spec Section 20.16: "The generated static initialization code is placed after any user-defined
    static initialization code."
    David Ezzio
    Eric Borremans wrote:
    >
    Hi,
    I have been hunting down a NullPointerException for half a day to come to
    the following conclusion.
    My constructor calls a method which uses static variables. Since an intance
    of my class is created in the static block when the class is loaded, those
    statics are probably not fully initialized yet and the constructor called
    from the static block has those null pointer problems.
    I've considered moving the initialization of the static variables from the
    declaration to the static block. But your code is inserted BEFORE any other
    code. Therefore not solving my problem.
    Two questions:
    1) what would be a solution to my problem? How can I make sure my static
    variables are initialized before the enhancer generated code in the static
    block calls my constructor? Short of decompiling, changing the code and
    recompiling.
    2) Why is the enhancing code inserted at the beginning of the static block
    and not at the end? The enhancements would be more transparent that way if
    the static variables are initialized in the static block.
    Thanks,
    Eric

  • Static and variable

    I declare a variable inside a static method. Once I exit the method, is the variable eligible for garbage collection?

    user8742475 wrote:
    I declare a variable inside a static method. Once I exit the method, is the variable eligible for garbage collection?All variables declared inside a method (including any method parameters) are local to that method and go on the stack. There's no GC involved. The variable simply ceases to exist when the stack frame is popped when the method ends.
    Make sure, however, that you understand the difference between a variable and the object it points to. When your method ends and your variable goes out of scope, the object it pointed to might become eligible for GC. It depends on whether any other reachable references are still pointing to it.
    Also, variables don't get (directly) GCed. Objects get GCed. And while it's true that GCing an object includes reclaiming all of its non-static member variables, we don't really talk about the individual variables being GCed, just the object.
    Edited by: jverd on Aug 3, 2011 7:05 AM

  • How to compare substitution variable name to static member names (not data)?

    Is there a way to write a BSO member formula that compares a substitution variable against the name of a static member (not the data value of the member)
    For example, I have a BSO database that has the sub variable &CurrMth (which is set the real current month), and I am trying to use it in the Q1/Q2/Q3/Q4 member formulas
    IF(&CurrMnth <> "Jan" AND &CurrMnth <> "Feb")
       "Mar";
    The intention of the above is: if &CurrMnth is neither Jan nor Feb, then the Mar value will be used. However, the system is actually comparing the values of &CurrMnth and Jan/Feb, rather than the names/text string of "Jan"/"Feb".
    I have been looking around the tech references, but I was unable to find any functions that will compare the text strings of member names as they all appear to compare against the data itself.
    Please let me know if there are any ways to compare the member names themselves in a member formula, not the data values.
    Thanks!

    Thanks Celvin, that looks like it works!
    However, I do need to do the same function in the equivalent quarter members in our ASO cube as well. Do happen know know if there's a similar MDX function I could use in the ASO cube to acheive the same result? I was using the following to achieve this in ASO (which obviously did not work):
    IIF([Time Periods].[Jan] <> &CurrMth AND [Time Periods].[Feb] <> &CurrMth,
       [Mar],

  • Interface member variable by defaultly static ?

    Hi,
    The interface member variable by defaulty public,static,final.
    But i have one doubt.
    It is public because it has to access out side the interface.
    It is final because the value never changes
    Why it should be static ???
    Thanks,
    Narendra babu.B

    Member variables are an implementation detail. Java does not allow multiple implementation inheritance. Java does allow multiple subtyping through interfaces. So interfaces can't have member variables.
    Consider the diamond of death:
    interface A
        int x;
    interface B extends A
    interface C extends A
    interface D extends B, C
    }See the problem now?

  • How to use member variable to all my pakages

    i want to use some member variables to all my packages in my project how to declare it.

    why doesn't declaring it public works for you. You may declare it public static, if want to get rid of creating objects of the containing class.

  • Accessing member variable

    Hello techies,
    Iam trying to access the member variables of an object which is added to arrayList.
    I had 2 arrayLists.
    Now i am converting it into Object[] using toArray()
    Now iam comparing these two arraylists.
    Now iam trying to access the memeber vairables of each object which is added to arraylist .
    But iam unable to access the member variable of each object.
    Object a[] = a1.toArray();
              Object b[] = a2.toArray();
              for (int i = 0; i < a.length; i++) {
                   System.out.println("inside for loop");
                   for (int j = 0; j < b.length; j++) {
    // a.
                        int o = compareObjects.compare(a[i], b[j]);
                        System.out.println("returned value is" + o);
    Here is my code::
    import java.util.*;
    import java.io.*;
    import java.lang.*;
    class exampleObject implements Comparator {
         String s = null;
         int i;
         int o;
         public exampleObject() {
         public exampleObject(int p, int q) {
              i = p;
              o = q;
         public int compare(Object o1, Object o2) {
              exampleObject k = (exampleObject) o1;
              exampleObject kk = (exampleObject) o2;
              // System.out.println("k.i"+k.i);
              // System.out.println("kk.i"+kk.i);
              if (k.i == kk.i) {
                   System.out.println("inside if condition" + k.i);
                   System.out.println("same i values");
                   if (k.o == kk.o) {
                        System.out.println("kk.o");
                   } else {
                        System.out.println("same p values");
                        return kk.o;
              return k.i;
    class ArrayListObjectCompare {
         // public static BufferedReader readFile;
         public static exampleObject ex;
         public static void main(String args[]) {
              ArrayList a1 = new ArrayList();
              ArrayList a2 = new ArrayList();
              ex = new exampleObject(2, 3);
              exampleObject ex1 = new exampleObject(3, 4);
              exampleObject ex2 = new exampleObject(4, 5);
              exampleObject ex3 = new exampleObject(5, 6);
              exampleObject ex4 = new exampleObject(6, 7);
              a1.add(ex);
              a1.add(ex2);
              a1.add(ex4);
              a2.add(ex1);
              a2.add(ex3);
              exampleObject compareObjects = new exampleObject();
              Object a[] = a1.toArray();
              Object b[] = a2.toArray();
              for (int i = 0; i < a.length; i++) {
                   System.out.println("inside for loop");
                   for (int j = 0; j < b.length; j++) {
    // a[i].k(-----here iam getting error);
                        int o = compareObjects.compare(a[i], b[j]);
                        System.out.println("returned value is" + o);
    can any tell me how to access the member variable of each object which is added to arrayList.
    I will be very thankful if any body replies or modifies my code.
    thanks(inadvance),
    ramu

    I'm not sure if they work 100% correctly yet after the forum "upgrade" last week, but please use code tags (see button above posting box) when posting code.
    You need to cast your Object back to exampleObject:
    exampleObject myObj = (exampleObject)a[0];
    System.out.println(myObj.i);Or, try using the other "toArray" overload:
    exampleObject a[] = a1.toArray(new exampleObject[a1.size()]);Then your "a" array elements are already of class exampleObject, and you don't need to cast each element individually.

  • [SOLVED] Passing a non-static member function as a function pointer

    I need to pass a function pointer to a public method to a system call, nftw() to be precise.
    I know that member functions don't match the required signature because of the hidden 'this' pointer, but
    the only way to work around that is by using a small wrapper function that makes use of a global variable (the object of which I want to call the method).
    Speaking in code, this is the way I've solved the problem currently:
    // create a global variable here
    static MyObject obj;
    static int myObject_method_wrapper(const char *fpath, const struct stat *sb, int tflag, struct FTW *ftwbuf) {
    return obj.handleDirEntry(fpath, sb, tflag, ftwbuf);
    // somewhere in main()
    nftw(walkroot, myObject_method_wrapper, 20, FTW_PHYS);
    Now, my question: Can't this be done without a global instance of MyObject? It is pointed out here that other ways are existent, but sadly they are not mentioned.
    Glad if someone could help me out!
    Last edited by n0stradamus (2012-04-24 22:59:47)

    I think you are stuck:
    1. You are not in control of the interface (of nftw), and furthermore,
    2. You are not in control of any of the parameters sent to the callback.
    nftw has no idea which one of your objects it is supposed to reference, and
    there's no apparent way to tell it.
    But given this situation, are you sure it makes sense to use a non-static
    member?  It seems kind of strange to me-- any instance-specific data is
    necessarily going to be independent of the function calls!  So even if you
    engineer something to avoid using a global, whatever you engineer is still
    going to involve some *arbitrary* instance of your class (e.g. peterb's
    solution, which uses the most recently created instance).  The arbitrary-ness
    doesn't feel right, since it sort of implicitly says that none of the instance
    data is important.  No important instance-specific data sounds like static...

  • Static member-class varaiable instanciation

    Hello,
    I have an inner class which I'm trying instanciate as a static variable. here is the code:
    public class A {
    protected static B b;
    private A (){} //private constructor because B is singleton
    class B {
    //some code
    =========================================================
    I cannot say
    protected static B b = new B();
    because new operator returns this.new_instance_of_B, and "this" cannot be referenced from the static constant...
    How can I instanciate this variable (b)?? Thank you,
    Elana

    You could make the class static but depending on how the class is written you might be better off just instatiating b in your constuctor. I question declaring b protected. You can not subclass a singleton (no public constructor), therefore there is no reason to declare b protected. If you want other classes to access b from inside the package just use package level (default) access. Having a static member of a singleton that isn't private seems to violoate the purpose of the Singleton pattern though. I don't know what you are trying ot do but I would declare your class like this.
    public class A {
        private static B b;
        private A (){
            b = new B();
        private class B {
            //some code
    }

  • Linker error 2005 when using member variable of type CNiGraph in CW++

    Hi,
    when I try to use a member variable of type CNiGraph I receive linker errors LNK2005, e.g.:
    msvcrtd.lib(MSVCRTD.dll) : error LNK2005: __CrtDbgReport already defined in libcmtd.lib(dbgrpt.obj)
    The project was created with the NI Measurement AppWizard.
    CW Version 3.0.1(549)
    OS: Windows 2000
    Thank you for your help.
    Uwe Gratzke

    This really isn't enough info about your project to give a definative answer, but one possibility is that you could have set up your project to be statically linking to the MFC libraries which we don't support. It could be a lot of other possibilities also. If you would like, you could have our support engineers help you with the project by sending it to us via http://www.ni.com/ask.
    Best Regards,
    Chris Matthews
    Measurment Studio Support Manager

  • Can't see member variables when debugging with jrockit

    Hi all,
    I'm using WLS 8.1.4 with jrockit and trying to do remote debugging while connecting from IntelliJ Idea 4.5.4. Everything works fine except that I can't see a class's member (or instance) variables in the debugger. I can see static and local variables, step through the code, etc. If I switch to Sun's jvm that came with WLS (1.4.2 05) I can see member variables. Is there a setting to change this or is it a known issue? I'm using -Xdebug -Xrunjdwp:transport=dt_socket,server=y,address=5005,suspend=n as my startup args.
    thanks

    I just check with IntelliJ support on this issue. They say that its a known issue with IntelliJ 4.5. According the them a fix has been implemented and debugging of member variables is possible in IDEA 5.x versions.

  • Making  member variable as serializable

    Hello Techies,
    can we make a perticular member variable of a object as serializable.
    let us suppose we are having one class
         class a
                   int i =0;
                  String s = "ramu";
                  public void show()
                          s.o.p("this is xxx");
       class b
             public static void main(String args[])
                       a   x = new ();
       }can I make the variable i as serializable. if so how can it be??
    regards,
    ramu.

    What do you mean? You can make classes serializable, not member variables.
    There's the keyword "transient" (look it up in your favourite Java book) which will prevent a member variable of a class from being serialized. So if in your class a you only want the value of i (and not the value of s) to be serialized when you serialize an instance of class a, you should make s transient.

  • Static member reference

    Hi:
    I have a question regarding how static members are referenced. Here is a simple example.
    public abstract class A {
    public static int a = 1;
    public void printA()
    System.out.println(a);
    public class B extends A {
    public static int a = 2;
    public class C extends B {
    public static int a = 3;
    Now when I do this:
    A x = new A();
    B y = new B();
    x.printA();
    y.printB();
    they all print 1, but I was expecting x.printA() to print 2 as x's a is 2 and y.printA() to print 3 as y's a is 3.
    I have a class structure where each class has some static members, now i am writing methods in each class to access these static members
    repeatedly. They are the same code, just in different classes. I would like to just put these code into a super class so I would not need to
    rewrite the same thing over and over again. Somehow I have not found a way.
    To me, rewriting the same piece of code usually indicates bad programming. But I am not smart enough to figure out a way.
    Is there a way?
    Thanks a lot in advance.
    FTC

    freetochoose wrote:
    my problem is quite practical.
    I have many classes that all have the same kind of static members. For example, each class has a filename and database table name where i save the data.
    so if i have a super class that has a method like
    savetofile() or savetodatabase()
    each subclass will supply the filename and table name.
    but as my example shows
    in the super class method public void savetofile(), filename will only refer to the super class's static member, and will not
    refer to the sub class's static member, filename, which is what i want.Then don't use static members, use instance-variables, or make the superclass abstract and add abstract methods to get the filename / table name, so every subclass needs to implement that method to return the correct name.
    so i have written code and tested out that in a super class, a reference to a static member is only to that class's static member.
    it will not refer to a subclass's static member even when the object is an instance of a subclass.
    in the end, i concocted the method using java reflection, getClass().getField(this, staticMemberName).toString()
    and it works the way i want it. but somehow, it does not seem too elegant in the sense that reflection should be
    used rarely and i am wondering if there is a better way of doing the same thing without reflection.Never use reflection unless you really have to, and you don't.

  • Static member varaibles

    Hi,
    What is the advantage in having static member varaibles in a Singleton class?
    Since, the class itself is Singleton, is there any advantage in having static member varaibles in the class?
    Thanks in advance,

    If the class is a Singleton that means that onlyone
    reference to the class exists. As such, you can
    freely make all member variables instancevariables.
    Most, but not all. Think of the Singleton reference
    itself. :) Very true!
    Or a reference counter in case you later
    need it to be a "multipleton". And it might also have
    some utility methods...
    Then I would humbly assert it is no longer a Singleton.
    for some reason, JBuilder's code check advises to
    declare all methods that aren't accessing non-static
    members as static. I don't know whether to follow
    that or not. I prefer work to be done by objects.I've had that confusion as well. Why not simply declare a static private variable and provide static public accessors and mutators? The alternative is a single, Singleton instance which has its own local variables, IMO. But both seem valid to me.
    - Saish

  • SwingWorker and member variable thread safety

    If I have the following code:
    import javax.swing.SwingWorker;
    public class TestWorker extends SwingWorker {
         private String result = "Default";
         @Override
         protected Object doInBackground() throws Exception {
              if (Math.random() > 0.5) {
                   result = "Bigger";
              else {
                   result = "Smaller";
              return null;
         @Override
         protected void done() {
              System.out.println(result);
         public static void main(String[] args) {
              new TestWorker().execute();
    }Am I guaranteed to always get an output of either 'Bigger' or 'Smaller' or will I sometimes get 'Default'? The crux of the question is, will the background thread which updates the member variable 'result' be guaranteed to flush its cache by the time the done() method is called on the Event Dispatch Thread? I know I could guarantee the freshness of 'result' by making it volatile but I just wanted to know out of intellectual curiosity if SwingWorker tackles this.

    The SwingWorker object is still strongly reachable from other places even though it is no longer reachable from your main() method.
    In short, the work that is done on the EDT is a Runnable object that has a reference to the SwingWorker. So even through the SwingWorker may have finished running, there are still references to it so it cannot go completely out of scope (and thus, it's variables cannot go out of scope). The references to the SW are from the runnable, which is referenced from the EventQueue (i.e, EventQueue.invokeLater()), which is either static or referenced from the EDT.

Maybe you are looking for

  • Slew of N97 problems.

    I'm sure some of these may have been addressed in the n97 bugs thread, but I do nto have time to read through 500 posts, and a post in that will simply be buried and forgotten in moments, hopefully I can find some hints in here. the problems I am hav

  • To change the Transport request nUmber

    Hi i have created some programs with diffrent request numbers and task numbers now i need to change the descriptions , requst numbers for the same programs how to change that Thanks in advance

  • Extension Mobility not working properly

    Dear All, I would like to ask about extension mobility on my Cisco Unified Call manager 8.5. The problem is when I press services button then Extension Mobility the put the User ID and Pin, the login was successfull but after that there's no change o

  • HT1937 Hi Dear, My Wifi and Bluetooth is not on what can do plz help me!

    Hi i have iPhone 4s since 4 month my Wi-Fi and bluetooth is not connceting or on what do i do plz help i am very upset

  • Switch strategy: AT&T phone first, then iPhone?

    I'm not an AT&T customer. My Sprint contract ends in October and I'll get my iPhone then. So I was wondering how well this strategy would work: 1. Sign up with AT&T and get a subsidized phone with a removable SIM card. 2. Sign up for the iPhone as an