Static members and inheritence

class A {
   public static int x = 111;
class B extends A {
    public static int x = 222;
    void foo(A a) { System.out.println(a.x); }
...If I call "foo(new B());" it prints "111".
How to change A/B or foo() so that such call will print "222", without making the field non-static (waste of memory) or using reflection (waste of time) ? I need exactly 1 int per class and its value cannot be hardcoded.
Thanks

As for reflection, unfortunately it is still much slower than direct access (more
then 100-200 times). 100-200 times slower than something extremely fast, is still pretty fast.
I'm still not entirely convinced you have a problem here.
Since the values are constant (once they have been initially defined) you can indeed use a hashmap like that. I would probably mix it with reflection:
  final int getX() {
         Integer x =  (Integer)xMap.get(this.getClass());
         if (x == null){
            // load the value via reflection
           // put it into the map for next time
         return x.intValue();
    }The reflection hit only occurs once for each class. Thereafter your only hit is looking the value up in the Map. Still probably not quite as fast as direct access.
If the field values were not constant, I would probably cache the Field objects. As I understand it, the hit taken with the reflection APIs is more the looking up (introspection). Once you have the fields/methods cached access is pretty fast.
But I agree with Adeodatus. Its a wonky solution. It might be better to pull that value out of the class, or just have it as an instance variable.
Where/how are these values discovered anyway? Obviously at runtime - through a database/properties file? How do you set the values for them all?

Similar Messages

  • Static blocks and inheritence

    public class SubClass extends SuperClass {
    static {
    System.out.println("Sub class being called");
    SuperClass.setS("TREX");
    public class SuperClass {
    protected static String s;
    static {
    System.out.println("Super being called ");
    static public setS(String t) { s= t; }
    static public String getS() { return s; }
    public static void main(String[] args) {
    System.out.println(SubClass.getS());
    The above prints
    "Super being called"
    null
    Why is "Sub class being called " not printed? It looks like
    the subclass static block never gets called.?

    hi
    may be i did not something catch right concerning static blocks and inheritence
    (jdk1.5x)
    please have a look at the following example.
    1. static block in subclass is only executed if the static vars are not defined final. why is this?
    2. why does not any subclass has its "own" hashtable colors?
    thanks
    hanspeter
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    import java.util.Hashtable;
    abstract class ParentStaticBlock  {
         static final Hashtable<Integer, String> colors = new Hashtable<Integer, String>();
         static void putColor(int colNumber, String colName) {
              colors.put(colNumber, colName );
         static String getColorNameFor(int colNumber) {
              return colors.get(colNumber);
    final class Child1StaticBlock extends ParentStaticBlock {
         public final static int ROT = 0x00000D;
         public final static int GELB = 0x00000E;
         static {
              System.out.println(" hello, here static block of Child1StaticBlock...");
              putColor(ROT, "ROT");
              putColor(GELB, "GELB");
    final class Child2StaticBlock extends ParentStaticBlock {
         public /*final*/ static int GRUEN = 0x00000A;
         public /*final*/ static int BLAU = 0x00000B;
         static {
              System.out.println(" hello, here static block of Child2StaticBlock...");
              putColor(GRUEN, "GR�N");
              putColor(BLAU, "BLAU");
    public class TestChildStaticBlock {
          * @param args
         public static void main(String[] args) {
              int colNo;
              String colBez;
              System.out.println("Static elements class Child1StaticBlock ->");
              colNo = Child1StaticBlock.GELB ;
              colBez = Child1StaticBlock.getColorNameFor(colNo);
              System.out.println("color yellow has number >" + colNo + "< and label >" + colBez + "<");
              System.out.println("");
              System.out.println("Static elements class Child2StaticBlock ->");
              colNo = Child2StaticBlock.BLAU ;
              colBez = Child2StaticBlock.getColorNameFor(colNo);
              System.out.println("color blue has number >" + colNo + "< and label >" + colBez + "<");
              System.out.println("");
              System.out.println("contents of hashtable(s) ->");
              System.out.println("ParentStaticBlock.colors:" + ParentStaticBlock.colors);
              System.out.println("Child1StaticBlock.colors:" + Child1StaticBlock.colors);
              System.out.println("Child2StaticBlock.colors:" + Child2StaticBlock.colors);

  • Static vs Non--Static members

    I'm having some trouble trying to understand the differences between static and non-static members.
    I've read a few online information about static members, but I don't understand the purpose of static members.
    Can someone try to explain the main points of static members and the differences between static and non-static members?

    I'm having some trouble trying to understand the
    differences between static and non-static members.
    I've read a few online information about static
    members, but I don't understand the purpose of static
    members.
    Can someone try to explain the main points of static
    members and the differences between static and
    non-static members?Static means only one per class. If you have a Class and generate 20 objects of this class or more, they all share the same copies of any static variables. This is as opposed to instance variables of which each Object has its own. If an object changes one of its instance variables, this doesn't affect another object's instance variables.
    Having said this, however, vague and general questions are great if you are face to face with a tutor where you can have a conversation but are very difficult to answer in this format. Your best bet is to go through several online articles (and there are many good ones, just google for them) and then coming back with specific questions. Another option is to go through a book or two. Most have a chapter covering this.
    Message was edited by:
    petes1234

  • Factory class and static members

    I don't understand very well why sometimes you can find a factory class (for example for the xml parsers). What's its aim?
    And why sometuimes, instead of a constructor, some classes have only static methods that returns a reference to that object?
    Anyone can tell me?
    Thanks

    Static memebers can be used in places where instances of its enclosing class is not neccesary.Only a method is required to be executed. Let me tell you with an example,
    class ConnectionPool {
    public static giveConnection(int index) {
    In the above example, our objective is to use only the method public static giveConnection(int index) {} , and not any of the other attributes of this class. You have 2 ways to use this method : One is, you can instantiate ConnectionPool p = new ConnectionPool(); . Second is , just use ConnectionPool.giveConnection(2);
    The first solution may create instance and obstruct your performance. Seond one does not do that. All invokers of this method do not instantiate and occupy space.
    Usually, factory classes have static members. Because these classes are used as a supporting processing factory. Theses members can be considered as utility methods. Hence static property will better suit for them. This answer will also tell you that the use of constructors here is not neccessary.
    Hope this has helped you.
    Rajesh

  • JVM and static members of classes

    Hello Experts,
    I have applet project. Recently I reorganized the code and I made so many class members "static".
    The applet starts from javascript link from browser. When I start it at first time, everythink is OK,
    but when I start it second time there is a problem with these static members(Actually they are dialogs,
    panels, vectors and s.o.) They are saved in the memory in some way. When I close the parent browser(the browser
    that holds the javascript link) and then start again, everything is OK, because I starting applet for
    first time.
    How can I make the following calls like the first one ?
    Please help me !
    Best Regards,
    Valeri

    When u are opening a browser the static variables
    are persistance unless u closed the window.
    so while u are opening the second time the
    static variables are not initalizing.
    so if u remove the static .
    Or after displaying the applet u initialize the
    staic variable.

  • Life and memory space for static members of a class

    hi,
    as we all know that instance members reside on heap inside object to which they belong, where do the static members reside on the heap or on stack..

    All objects reside on the heap.*
    *I think Java 6 or 7 may allow purely local objects to live on the stack, but if an object is referred to by a member variable--whether static or not--it will live on the heap.                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Static class and clustering

              I have a static class that I use to cache some values during a batch process. The
              batch process uses a JMS queue to parcel our identical units of work to MDBs.
              I want this to scale using a cluster with the same MDBs on multiple machines.
              Everything works fine except that I can't figure out how to tell my cache to clear
              itself out on every node between batch runs. Is there a pattern or solution to
              this problem?
              What I've tried is to create a stateless session bean method that clears my cache.
              At the begining of my batch job, (which is a stateless session bean call) I call
              this method on each server in the cluster by getting the remote interface for
              the stateless bean via the different URLs of the servers. However, the session
              bean method always executes on the one server where I make the call. It's as if
              WebLogic gives me back a local interface instead of the remote interface that
              I asked for.
              Any ideas would be appreciated.
              Colin
              

    ... static class and static method.I have never heard of a thing called "static class". Perhaps you mean a class with only static members?
    My design approach (which is bound to needs of the moment and seldom to library-development or future re-use, since both is harder than most developers realize) is to develop straight without caring too much about static or not. When a method is done, debugged and works well, it happens that other objects access this method as well.
    It may happen that I just want to use this single method and almost nothing else of the object. If that is the case, I can start looking if it's a Good Thing(tm) to make the method static, so no object creation is needed just for the one method. Sometimes it can be done, sometimes not.
    But that's just me and you'll find quite a lot of coders that'll advice you to decide what's static and what not before you start coding. And that's as good an advice as most others you can get.
    In the end it's your decision, so start fiddling around and see what fits best for you.
    -T-

  • Static block in superclass to initialize static members in subclasses

    I am trying to create several classes that are all very similar and should derive from a super class because they all have common members and are all initialized the same way. I would prefer every member of my subclasses to be static and final as they will be initialized once and only once. I can not figure out the best way to make this work. Here is an example (using code that does not work, but you can see what I am trying to do):
    class Super
        protected static final String initializedInEachSubclass;
        protected static final String alsoInitializedInEachSubclass;
        // these need to be accessed from anywhere
        public static final String initializedInSuperclass;
        public static final String alsoInitializedInSuperclass;
        // this static initialization block is exactly the same for every instance
        static
            // initialize these based on what the subclasses initialized
            initializedInSuperclass = initializedInEachSubclass + alsoInitializedInEachSubclass;
        private Super () {} // never instantiated
        public static final String getMoreInfo ()
            // the same for each instance
            return Integer.toString (initializedInEachSubclass.length ());
    class Sub1 extends Super
        static
            initializedInEachSubclass = "My String for Sub1";
            alsoInitializedInEachSubclass = "My Other String for Sub1";
        private Sub1 () {} // never instantiated
    }The problem with the above code is that the static block in Super uses static final variables that have not been initialized yet. I can't make Super abstract. If I initialize the final variables in Super, then I can not reinitialize them in Sub1. But if they are not final, then they could be changed after being initialized (which I would rather not allow). I could make everything protected and not final and then make public get... () methods, but I like accessing them as attributes. It seems like this should be possible, but everything I have tried has led me to a catch-22.
    Any ideas on how I can put all my redundant initialization code in one place but still allow the subclasses to initialize the static members that make each of them unique? I will be happy to clarify my examples if you need more information.
    Edited by: sawatdee on Jan 3, 2008 9:04 AM

    sawatdee wrote:
    I am basically trying to avoid having redundant code in several classes when the code will be exactly the same in all of them.That's the wrong reason to subclass. You subclass to express type specialization. That is, a Dog IS-A Mammal, but it's a special type of Mammal that implements certain common mammal behaviors in a dog-specific way. A LinkedList IS-A List, but in implements common list operations in linked-list-specific ways.
    I don't really need to have the static final members in a superclass (and I don't even need a superclass at all), but I don't know how else to execute a big static initialization block in several classes when that code is exactly the same in all of them. Without knowing more details about what you're trying to do, this sounds like a case for composition rather than inheritance. What's now your superclass would be a separate class that all your "sublasses" have a reference to. If they each need their own values for its attributes, they'd each have their own instances, and the stuff that's static in the current superclass would be non-static in the "subs". If the values for the common attributes are class-wide across the "subs", the contained former super can be static.
    public class CommonAttrs {
      private final String attr1;
      private final int attr2;
      public CommonAttrs(String attr1, int attr2) {
        this.attr1 = attr1;
        this.attr2 = attr2;
    public class FormerSub1 {
      private static final CommonAttrs = new CommonAttrs("abc", 123);
    ... etc. ..

  • Static data and multiple CPUs

    Hi, could anyone explain how data in static data (like static classes, static members of a class etc.) are handled across multiple CPUs in a multi-threaded application?
    Thanks,
    Lei

    nope
    its got way too much to do with the JVM and OS
    thread scheduling and optimisation (particularly in multiple CPU is a nightmare)
    it would also (if the optimisation went that far) depend on the architecture of the CPU in question..
    Althon MP each have processor cache (no surprise i guess) but the clever bit is that there is a very high speed buss to share the cache
    so in that case (i would guess) that one CPU could handle the static methods for a particular class, or it might be that either CPU could excecute code held in the cache of the other chip
    i really dont think that there would be set rules for how java deals with such low level optimisation

  • Your Opinions: Inner Classes Need static Members

    Hi All,
    I want to solicit opinions for a minor change to the way inner classes work. I submitted this as an RFE to Sun and they rejected it, really without giving a reason. I'd like to know your opinions. If there is strong support I will repost the RFE.
    As you probably know, inner classes cannot have static members. The following generates a compiler error:import java.util.*;
    public class MyClass {
       class MyInnerClass {
          // Next line causes compiler error...
          static Map m = new HashMap();
    }In order to get around this you have to make the Map variable a static member of the containing class:import java.util.*;
    public class MyClass {
       static Map m = new HashMap(); // so much for encapsulation...
       class MyInnerClass {
    }I am suggesting that inner class be allowed to contain static members. Here's my reasoning...please comment:
    There are times when members (i.e., fields and methods) rightfully belong to the class as a whole, not to any particular instance of a class. I'm sure we've all found times when it was necessary to have static members in our classes. The same issues that necessitated using static members in top-level classes make them desirable for inner classes as well.
    Designing a class as an inner class is a step toward encapsulation. By forcing static members that logically belong in an inner class to be declared in the containing class is to crack the encapsulation, IMHO.
    Even though a containing class has access to all of an inner class' members (including private members) and vice versa, I think the notion of inner static members still is more OO-ish.
    What are your opinions? Would allowing inner classes to contain static members make Java more object oriented? I think it would.
    Technically, I don't think there's any reason this cannot work since the JVM has no notion of inner classes, per se.
    What do you think?

    an inner class is effectively a non static instance
    variable of its enclosing class. Instance member, but not a variable. it's a class, a type, not a variable.
    >
    I think the problem here is that making a field static
    means more than just that that field and its value are
    common to every instance of the class. It means that
    the value is valid without an instantiation of that
    class.
    Since the class itself must be instantiated (it is
    not static), What do you mean, excatly, by "_must_ be instantiated"? You are not ever "required" to instantiate anything unless you want to use it.
    you can't have static member data inside it. I don't see how this follows from the previous part of the statement.
    How would you reference the static member data of
    the inner class? You would have to specify an
    instance of the inner class, and since this breaks
    the meaning of static, you can't have static members
    in an inner class.How about outerObj.InnerClass.staticMember The syntax is well defined. The question at hand is, do we really want to allow this? The syntax to do this should only be an issue after that question has been answered in the affirmative. The people at Sun have decided not to allow it, so for now, syntax is a non-issue.
    >
    if you wanted a static member in an inner class you
    could put it in a super class of the inner class...Or in the enclosing class, as suggested in the orginal post.

  • Inheritance of static members

    I realise that this is a very basic question but I'm hoping that someone will explain the answer to me. I have two classes, one extends the other and both have instance variables assigning a name to the object when it is instantiated. The superclass also has a print method which displays the name of the object. When the superclass and subclass are tested, both print their own names. However, if I make the name variables static, as well as the print function in the superclass, when I call printName on both superclass and subclass, both print the name of the superclass. Why? I had understood that static members were inherited in the same way as instance members.
    public class MySuper{
         protected static String myName = "Super";
         protected static void printName(){
              System.out.println(myName);
    public class MySub extends MySuper{
         protected static String myName = "Sub";
    }MySuper.printName(); prints "Super"
    MySub.printName(); prints "Super"

    A static method uses static variables of the class
    itself unless otherwise specified.So why doesn't MySub use it's own variables?
    It does; the problem is that there are two variables with the same name. By default it is the variable of the class where the method is declared in, so MySub.printName() uses the variable MySuper.myName. Declaring a new variable in the subclass, static or not, does not override or replace the variable in the superclass, it simply hides it from the methods of the subclass.
    When you inherit a method, it is not copied intothe SubClass, it is only available to be
    used from this SubClass.
    That was what I was trying to imply. That the
    printName method is inherited by MySub and is
    available to be used by MySub.
    So MySub can use printName() (from MySuper) and
    executes this on it's own variable myName="Sub".
    No, it uses the superclass variable; subclass variables don't replace superclass ones.
    Why
    is that not happening with my static example when
    that's exactly what happens with my non-static
    example? Where is the difference?
    There is no difference; you will see the same thing happen with instance methods:class MySuper {
        String myName = "Super";
        void printName() {
           System.out.println(myName);
    class MySub {
        String myName = "Sub";
    }When you call printName for an object of class MySub, you'll see "Super" printed.

  • Why global var can be initialized with a static method and not by other static global var declared after its usage

    Take this:
    class test
    static int i=j;
    static int j=10;
    this will give illegal forward reference ....
    but this will compile successfully ..
    class test
    static int i=test1();
    static test1()
    return 20;
    plz assume we have main method in both cases ..
    java would be loading all static members first and would be assigning default values .. and then will be running all the initializers from to bottom ..
    Why second case is a compile success and not first .. as in second also test1 method is declared after its usage ..
    Plz help.
    Thanks
    Abhishek Roshan

    Why second case is a compile success and not first .. as in second also test1 method is declared after its usage ..
    Because the implementors of Java intentionally chose to do it that way.
    There are TWO stages to the process: preparation (which occurs first) and initialization.
    See the Java Language Spec section 12.4.1 'When Initialization Occurs
    The intent is that a class or interface type has a set of initializers that put it in a consistent state, and that this state is the first state that is observed by other classes. The static initializers and class variable initializers are executed in textual order, and may not refer to class variables declared in the class whose declarations appear textually after the use, even though these class variables are in scope (§8.3.2.3). This restriction is designed to detect, at compile time, most circular or otherwise malformed initializations.
    Note the clause beginning 'may not refer to class variables'. And the authors give the reason for that restriction in the last sentence: detect circular initializations.
    Then if you check that referenced section 8.3.2.3 you will find this
    http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.3.2.3
    8.3.2.3. Restrictions on the use of Fields during Initialization
    The declaration of a member needs to appear textually before it is used only if the member is an instance (respectively static) field of a class or interface C and all of the following conditions hold:
      The usage occurs in an instance (respectively static) variable initializer of C or in an instance (respectively static) initializer of C.
      The usage is not on the left hand side of an assignment.
      The usage is via a simple name.
      C is the innermost class or interface enclosing the usage.
    When a method is used (your example 2) no circular initialization can occur because methods are not 'initialized'.

  • Main accessing non static members

    How can main access non static members itself being static?

    Why would you want to?
    Main has one purpose and one purpose only, it is there for kicking off a program and ensuring it closes cleanly. I know they generally don't teach this early on in programming classes, but in my opinion they should.
    You should never ever be doing any data processing in main. In some cases you may need to set data in main, like for example if the class the main is in is part of a larger project but you want to be able to test the class stand-alone without having to run the rest of the project. But in most cases main should do nothing with any data save the args, which should usually just be passed along.
    The reason behind this is simple, soon enough you will be writing programmes that span multiple class objects, only the main of the class you use to kick it off ever gets touched, so any data processing that is in the other classes main methods, never happens.
    Why you should learn how to get out of main now is, you may want to use the class you are writting now as part of a future project. But again you have the problem of unless this class is the one that kicks that project off, any processing in main does not happen. Plus what happens if you want to process the data in you are processing in main somewhere else? Code re-use of code in main is a no go.
    Plus, by getting out of main you no longer have to worry about that whole static/ non-static issue.
    JSG
    Sorry, this is just one of my pet-peeves

  • Can't remove static members using "Manage Group Members"

    Using the OAM 10.1.4.2 Group Manager app, I can remove static members from a group by modifying the Member property, but I can't remove members using the "Manage Group Members" page.
    When I search for members using that page, I get a list of the current members with an unselected checkbox for each. If I check the box next to a member and click Save, the member is not removed from the group. I turned on trace-level logging and saw that the correct user is being passed to the Identity server to be removed, but I haven't yet found anything to indicate why the removal doesn't work.
    Has anyone else run into this issue?
    Thanks,
    Matthew

    Hi Vinod,
    I'm running on Window 2003 against a Microsoft ADAM directory. I turned on diagnostics and re-ran the test using both "Manage Group Members" and modifying the property directly-- from what I can tell, the ldap modify only happens when I modify the property.
    (I had also noticed the problem with the instructions, but I eventually figured it out-- if I can get this working, I'll have to fix the verbiage before I deploy.)
    Any ideas? What platform and directory are you using?
    Thanks,
    Matthew

  • Singleton with static members only

    If I have a singleton class with static members only and I'd like to ensure that nobody accidentally instantiates the class, would it make sense to declare the class abstract? Or instead should I leave it non-abstract but make the no-argument constructor private? Or both?
    Which of these approaches would you recommend?
    Thanks.

    pros of using classical singletons (per Head First
    Design Patterns):
    1) It ensures that one and only one object is
    instantiated for a given class.This is effectively the same as using a non-instantiable class with all static members. You don't have an instance, but you have exactly one of it.
    2) It gives a global point of access like a global
    variableAgain, same thing with a non-instantiable class with all static members.
    3) It is only created when you need it (unlike a
    global variable) and thus wastes no resources if it
    is not needed.Again, same thing.
    Also, Java does not have global variables.
    Also, no variable in Java requires more than 8 bytes, and most are 4 or 2.
    4) Using a static self-contained class in place of a
    singleton can be a source of subtle, hard-to-find
    bugs often involving order of initialization of
    static code.Eh? Example please?
    5) Global variables encourage developers to pollute
    the namespace with lots of global references to small
    objects.What global variable? Java doesn't have global variables? How is a class full of statics any more a global than a "real" singleton?

Maybe you are looking for

  • Can i get my purchased music on a new pc?

    I've recently gotten a new computer, and want to put my purchased music on the new itunes on that new computer. is there a way to do this?

  • Steps for VEndor Evaluation

    Hi friends, Can you give me some idea about vendor evaluation ,its purpose ,steps from config to maitain ..report.. Thanks, Dharmveer

  • Macbook a1181 airport antenna cable socket problem

    Was replacing cracked screen on Macbook A1181 and in the process (quite unfortunately), both black and white antenna cables for the airport card were yanked from (ripped out of) their metal sockets.  Tried to delicately feed the cables back into thei

  • How can I remove speckles that appear in images in Photoshop CC?

    When I open an image in photoshop cc I get speckles of pinks and purples all over the image.  When I turn on the View Gamut Warning, the speckles disappear.  Also when I save an image as a file like jpg they do not appear.  How can I get rid of the s

  • What if my hard disk damaged?

    I'm using T61 with Vista Business. I used to restore my system frequently to original factory settings, whenever I faced any problem. My questions are: 1- Is it really danger to restore the system frequently? 2- How can I recover my system if the har