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. ..

Similar Messages

  • Help required in understanding of static blocks in java

    Hi ,
    Can some one help me in understanding the difference between static blocks in java....also what is the difference in declaring some static variables in a class and and declaring some variables in a static block? From an architecture viewpoint when should one use static blocks in Java?

    Static blocks are piece of code that can beexecuted
    before creating an instance of a class.static blocks are executed once, when the class
    itself is loaded by the JVM. They are not executed
    before creating each instance of a class.
    For example whatever you include in the mainn method will be
    executed without you having to create the instanceof
    the class using the new operator. So you can saythe
    main method is a static block.main is not a static initialisation block but a
    static method. a special case static method at that -
    it is only executed when the containing class is
    specified as a parameter to the JVM. (unless you
    specifcally call it elsewhere in code - but that
    would be bad form).
    in answer to the original post, static variables
    belong to the class. each instance of the class share
    the same static variables. Public static vars can be
    accessed by prefixing them with the class name. A
    static initialisation block can be used to
    initialise static variables. Variables declared
    within the static initialisation block exist only
    within the scope of the block.
    e.g.
    public class Foo {
    static Bar bar;        // static member variable
    // static initialisation block
    static {
    // variable declared in static block...
    String barInfo =
    arInfo = System.getParameter("barInfo");
    // ... used to initialise the static var
    bar = new Bar(barInfo);
    So is the only purpose of static initialization blocks is to initialize static variables? Does the initialization of static variables inside a static block make any difference in performance? If yes , then how ?

  • Why a static nested class instead of a static block?

    What difference does it make: using a static nested class on a static block?

    Surya-2010 wrote:
    What difference does it make: using a static nested class on a static block?Do you mean static initialization block?
    They're different concepts. A static initialization block is part of the construction machinery of a class. A static nested class is a class you want to treat as part of another class.

  • Error handling in static block

    Hello All,
    I have the following code
    static{
    abc();
    private static void abc() throws Exception{
    how do I throw error in static block because if I write
    static {
    abc() throws Exception;
    it gives error during compilation.
    How do I handle it.
    Sachin

    This is my code ...
    import java.io.FileInputStream;
    import java.io.*;
    import java.util.Properties;
    * @author sachin
    * This class is used setting the configurations
    public class Config{
         static String files_incoming;
         static String files_outgoing;
         static{
              try {
                   configurations();
              } catch (ICMSException e) {
                   LoggerCitiUtil.debug("Error in static block");               
         public static void configurations() throws ICMSException{
              Properties prop = new Properties();
              try{
                   Properties property = System.getProperties();
                   String systemPath = property.getProperty("MAIN_BASE_PATH");
              prop.load(new FileInputStream( systemPath + "bin/scp.ini"));
              }catch(IOException e){                 
                   LoggerCitiUtil.debug("File not loaded in Config class");               
              try{
    files_incoming=prop.getProperty("files_incoming").trim();;
    files_outgoing=prop.getProperty("files_outgoing").trim();;                                   
              }catch(Exception e){
                   LoggerCitiUtil.debug("Error in Config class");
                   e.printStackTrace();
    In the static block I want to throw new ICMSException(e);
    When I write this :
         static{
              try {
                   configurations();
              } catch (ICMSException e) {
    throw new ICMSException(e);
                   LoggerCitiUtil.debug("Error in static block");               
    But it gives unhandled Exception during compile time.
    Can anyone help me out ?.

  • Static Block vs Static Method

    Hi,
    what is the diff. b/w declaring the variable inside the static block vs static method?
    Why static block is executed first before static method?
    Once the class has been loaded inside the memory the static block will automatically executed by the compiler & it will executed before any static methods. What is the reason behind this why? static block is executed before static method? Please do provide an answer for this..
    Thanks,
    JavaLover

    Um.
    A static method is like a regular method; it only gets called if its...called.
    public class Test
      static
         //this stuff executes after being loaded into memory
      public static void main(string args[])
        //this main method is executed by the VM when you execute "java Test"
        staticMethod(); // this makes the program call staticMethod();
      public static void staticMethod()
        //this code wouldn't be executed if main(string[]) hadn't called it.
    }Hope everything I've said here is correct.

  • Non-static variable cant accessed from the static context..your suggestion

    Once again stuck in my own thinking, As per my knowledge there is a general error in java.
    i.e. 'Non-static variable cant accessed from static context....'
    Now the thing is that, When we are declaring any variables(non-static) and trying to access it within the same method, Its working perfectly fine.
    i.e.
    public class trial{
    ���������� public static void main(String ar[]){      ////static context
    ������������ int counter=0; ///Non static variable
    ������������ for(;counter<10;) {
    �������������� counter++;
    �������������� System.out.println("Value of counter = " + counter) ; ///working fine
    �������������� }
    ���������� }
    Now the question is that if we are trying to declare a variable out-side the method (Non-static) , Then we defenately face the error' Non-static varialble can't accessed from the static context', BUT here within the static context we declared the non-static variable and accessed it perfectly.
    Please give your valuable suggestions.
    Thanks,
    Jeff

    Once again stuck in my own thinking, As per my
    knowledge there is a general error in java.
    i.e. 'Non-static variable cant accessed from static
    context....'
    Now the thing is that, When we are declaring any
    variables(non-static) and trying to access it within
    the same method, Its working perfectly fine.
    i.e.
    public class trial{
    ���������� public static void
    main(String ar[]){      ////static context
    ������������ int counter=0; ///Non
    static variable
    ������������ for(;counter<10;) {
    �������������� counter++;
    ��������������
    System.out.println("Value
    of counter = " + counter) ; ///working fine
    �������������� }
    ���������� }
    w the question is that if we are trying to declare a
    variable out-side the method (Non-static) , Then we
    defenately face the error' Non-static varialble can't
    accessed from the static context', BUT here within
    the static context we declared the non-static
    variable and accessed it perfectly.
    Please give your valuable suggestions.
    Thanks,
    JeffHi,
    You are declaring a variable inside a static method,
    that means you are opening a static scope... i.e. static block internally...
    whatever the variable you declare inside a static block... will be static by default, even if you didn't add static while declaring...
    But if you put ... it will be considered as redundant by compiler.
    More over, static context does not get "this" pointer...
    that's the reason we refer to any non-static variables declared outside of any methods... by creating an object... this gives "this" pointer to static method controller.

  • Static block in java

    Suppose I have a class that has a static block in it
    public abstract class A {
        static {
        public A(){
        public void doSomething(){
    }And I have two other class viz Class B and Class C which inherit from class A. In this case will classB and classC each call the static block so that it gets called twice in all or will it be only once between Class B and Class C
    public class B extends A {
        public B(){
    public class C extends A {
        public C(){
    }

    And I have two other class viz Class B and Class C which inherit from class A. In this case will classB and classC each call the static block so that it gets called twice in all or will it be only once between Class B and Class CA static block (or static initializer) is executed only once per class, when the class is initialized. The fact that several other classes subclass the superclass does not imply it has to be reinitialized.

  • What type of member is a static block?

    In the the first chapter of the Java programming language 4th addition it states the following
    A class can have three kinds of members:
    1)Fields are the data variables associated with a class and its objects and hold the state of the class or object.
    2)Methods contain the executable code of a class and define the behavior of objects.
    3)Nested classes and nested interfaces are declarations of classes or interfaces that occur nested within the declaration of another class or interface.And this got me thinking about static blocks. Which category do they fit into among the above? Are they really methods? I don't think so myself although inside they can look like a method implementation. Also, the same goes for constructors, in JLS doesn't it say these are not methods either? There is no mention of them above though.
    Anyone have any views/thoughts/explanation on the above?

    Section 8.2 of the JLS (http://java.sun.com/docs/books/jls/third_edition/html/classes.html#8.2) reads:
    <quote>
    The members of a class type are all of the following:
    * Members inherited from its direct superclass (�8.1.4), except in class Object, which has no direct superclass
    * Members inherited from any direct superinterfaces (�8.1.5)
    * Members declared in the body of the class (�8.1.6)
    Members of a class that are declared private are not inherited by subclasses of that class. Only members of a class that are declared protected or public are inherited by subclasses declared in a package other than the one in which the class is declared.
    We use the phrase the type of a member to denote:
    * For a field, its type.
    * For a method, an ordered 3-tuple consisting of:
    o argument types: a list of the types of the arguments to the method member.
    o return type: the return type of the method member and the
    o throws clause: exception types declared in the throws clause of the method member.
    Constructors, static initializers, and instance initializers are not members and therefore are not inherited. [my emphasis]
    </quote>

  • Can we have try/catch in a static block in a class?

    hi All
    i have a question about put a try/catch block in a static block in a class to catch exceptions that maybe thrown from using System.xxxx(). in my custom class, i have a static block to initialize some variables using System.xxx(). in case of any error/exception, i need to be able to catch it and let the caller know about it. i tried to put a try/catch block in the static block, and tried to rethrow the exception. but it is not allowed, how would i handle situation like this? thanks for your help and advise in advance.

    You could just swallow the exception inside try/catch
    block, and instead of throwing it out, just set a
    static variable to allow checking from outside
    whether the initialization succeeded, or check within
    the constructor / methods of this class for
    successful initialization, and throw the exception
    then. You could even save that exception in a static
    variable for later.Ouch, ouch, you're hurting my brain. This would allow someone to ignore a (presumably) fatal error. Throw a RuntimeException as indicated. You can wrap a checked exception in an unchecked one if need be.

  • Use of functions in static block

    Hello,
    I have this app containing a static {} block. The reason it's there is to 1) provide a splash screen 2) have input dialog to process input string and check if it's valid in order to load app or not.
    In pseudocode it's like this:
    1 - get input string with showInputDialog()
    2 - check for the input string validity (a valid string is with prefix A-, C- or S-)
    3 - if string is valid, load the app
    4 - if string is not valid, proceed to step 1.
    As you may already see, there is going to be a lot of code (with if-else statements) to check for A-, C- and S- prefixed because I am using indexOf() function which takes only one parameter.
    I am considering a way to somehow check recursively, but for this I think I'll need a function to call indexOf() with A-, C-, S- and assess validity for each case.
    My question is, is there a way in the static block to have a function? Or can somebody please recommend an efficient approach to checking a string validity with different possibilities inside a static block as in my case, to avoid lots of if-else statements?
    P.S. My apologies for initially posting this thread in wrong section.
    Thank you!
    Victor.

    DrClap wrote:
    What's a function? And why are you particularly concerned about doing those things in a static initializer as opposed to in some other place?Hi,
    Sorry, I'm still thinking c++. I meant method. Something like of the form:
    static
    boolean valid = false;
    while string is not valid
    stringfrominput = showInputDialog();   
    //determine if string is valid
    valid = checkvalid(stringfrominput)
    //if possible to have
    boolean checkvalid(stringfrominput)
    recursively process stringfrom input based on A-, S-, or C- prefixes
    return boolean value
    }I have a jar app. It is Windows-based and runs as a TrayIcon application. If I include this process when class is loaded, this means that the app will be loaded with all its features. But I need to make sure that the app's features will be loaded only if certain conditions are met.
    I am not sure how else to approach this requirement without using static {} block.
    Thank you,
    Victor.

  • Clarification regarding static blocks.

    I can understand from this about the static initialization block. I just need one clarification. What is the difference between the blocks with and without the 'static' keyword? For eg., the following code prints 'Hello'
    class ClassWithStaticBlock {
              System.out.println("Hello");
    public class StaticBlockTester {
         public static void main(String[] args) {
              new ClassWithStaticBlock();
    }If I modify the class ClassWithStaticBlock like given below, I receive the same output. So, what is the difference between the two?
    class ClassWithStaticBlock {
         static {
              System.out.println("Hello");
    }Thanks.

    The static block is only run upon loading of the class. Well, during the initialization phase of loading it, but it amounts to much the same thing. Non-static initiializers are run every time the class is instantiated. Try this
    class ClassWithInitializers {
      static {
       System.err.printlln("Loading class");
        System.err.println("Initializing");
      public static void main(String[] args) {
        new ClassWithInitializers();
        new ClassWithInitializers();
        new ClassWithInitializers();
        new ClassWithInitializers();
    }See any difference?

  • Exception in static block + re-instantiating

    Hello All,
    I have got a number of unit tests and one that is running is causing an exception in a static block of a class which is expected. It throws an ExceptionInInitializerError which I catch in the unit test.
    But then another test is running using the same class and this time it should pass and create an instance of the same class as before.
    But instead I receive a java.lang.NoClassDefFoundError with no class name. Why? Can't I instantiate a class again once the initialisation had failed?
    Regards
    Jonas

    It's part of the VM Specification.
    See [2.17.5 Detailed Initialization Procedure|http://java.sun.com/docs/books/jvms/second_edition/html/Concepts.doc.html#24237]
    The first time,
    10. Otherwise, the initializers must have completed abruptly by throwing some exception E. If the class of E is not Error or one of its subclasses, then create a new instance of the class ExceptionInInitializerError, with E as the argument, and use this object in place of E in the following step. But if a new instance of ExceptionInInitializerError cannot be created because an OutOfMemoryError occurs, then instead use an OutOfMemoryError object in place of E in the following step.After that,
    5. If the Class object is in an erroneous state, then initialization is not possible. Release the lock on the Class object and throw a NoClassDefFoundError.

  • Static blocks and synchronization

    Hi,
    I have a question - I have a DAO class which basically caches some master data, and also reads a property file and caches the information. To do this I have written a static block :
    Class MyDAO {
    private static Properties sqlProp = null;
    priate Hashtable countries = null;
    static {
    initialize();
    private void initialize() {
    sqlProp = new Properties();
    //add values to sqlProp
    countries = new Hashtable();
    //add values in countries.
    I understand that a static block gets executed only once when the class gets loaded. Now my question is do we have to synchronize this initialize process, will there be any concurrency issues with the above code.
    If so how could I correct this , please let me know your suggestions..
    Thanks in advance..

    Thank you very much for the response..You are welcome. I hope you read my comment above as "Class initialization is thoroughly synchronized", which is what I intended :-)

  • 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 Blocks In Subclasses

    class A {
         protected static int foo;
         public static int getFoo() { return foo; }
    class B extends A {
         static {
              foo = 2;
    public class Test {
         public static void main(String[] args) {
              System.out.println(B.getFoo());
    }Output: 0
    I am accessing an inherited public function, but I am accessing it from the subclass. So shouldn't the static {} block of the subclass be called?

    I am accessing an inherited public function, but I am
    accessing it from the subclass. So shouldn't the
    static {} block of the subclass be called?Since the method is static the class B is never loaded and therefore the static{} block of B is never executed. Put a systemout in the static initializer, and add Class.forName("B"); followed by another System.out.println(B.getFoo()); to understand what is going on.

Maybe you are looking for

  • Save for web error in PS CC 14.2.1

    Whenever I try to save for web in PS I get an error message.  I've tried deleting the preference file as suggested in older posts, but it did not work.  I'm running Windows 8.1. Any help would be greatly appreciated!

  • Parent/Child requests in error

    Hi, I am actually working on a custom interface where I will have to pause the parent request when the child requests are running. APPS.FND_SUBMIT.submit_program ( application => r_stage_program.application_short_name , program     => r_stage_program

  • Can I connect an iphone 3gs to my tv to watch videos in apps, ie ActiveChannel?

    Can I connect an iphone 3gs to my tv to watch videos in apps, ie ActiveChannel or Niek Training Club?  TV is Samsung LED.

  • DS 5.2 patch 4 error log (on Windows 2000 sp4)

    I have a user that has sporadic DS shutdown problems. I honestly know very little about the DS and I'm hoping someone else has seen this. I requested two sets of error logs from: c:\Program Files\Sun\MPS\admin-serv\logs c:\Program Files\Sun\MPS\slapd

  • Bidding functionality in SRM

    Hi All, I have couple of queries on Bidding. To go with Bidding functionality 1. Is SUS is manadatory for Bidding ? 2.How Bidder will give RFX reponse with out SUS? Abdul Raheem