Class variable initialization

I have noticed that class variable initialization occurs AFTER the constructor is called.
Why is this, and is this intentional?
It has caused strange behaviour in my SE java applications I am porting to MIDP.
Thanks
- Adam

Hi,
Error 1:
The problem only arises if you use the unassigned variable:
int i;
int y = i; // Use of unassigned variable here
you can just assign a value to i to solve this:
int i = 0;
int y = i; // Use of unassigned variable here
Error 2 and 3 have to do with static and non-static, not with the initialization per se. This is how it works:
static members (e.g. fields) can be accessed using this syntax: <Classname>.<FieldName>, e.g:
public static class Helpers
public static int SomeDataValue { get; set; }
class Program
static void Main(string[] args)
Helpers.SomeDataValue = 22;
On the other hand, non-static members are accessed like this: <instance>.<fieldname>. So you always need an instance of a class to access the field:
public class Order
public int OrderNumber { get; set; }
class Program
static void Main(string[] args)
Order o = new Order();
o.OrderNumber = 12;
Rgds MM

Similar Messages

  • Class variables don't exist at initialize() time?

    Excerpt of Slam.mxml (default package):
    <?xml version="1.0" encoding="utf-8"?>
    <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
                      xmlns:s="library://ns.adobe.com/flex/spark"
                      xmlns:mx="library://ns.adobe.com/flex/mx"
                      xmlns:components="components.*"
                      minWidth="955" minHeight="600" width="1000" height="720"
                      initialize="Initialize()"
                      creationPolicy="auto">
         <fx:Script>
              <![CDATA[
                   protected function Initialize():void
                        Global.app = this;
              ]]>
         </fx:Script>
    </s:Application>
    Excerpt of Global.mxml (default package):
    <?xml version="1.0" encoding="utf-8"?>
    <fx:Object xmlns:fx="http://ns.adobe.com/mxml/2009"
                 xmlns:s="library://ns.adobe.com/flex/spark"
                 xmlns:mx="library://ns.adobe.com/flex/mx">
         <fx:Script>
              <![CDATA[
                   public static var app:Slam = null;
              ]]>
         </fx:Script>
    </fx:Object>
    When I run the app I get an error in Initialize() because Global is null.  Global is a class name and Global.app is a class variable, a static.  How can they not exist at initialize time?  Suggestions for how to deal with this?  Thanks.

    No, running just these files doesn't exhibit the issue for me.  I'm using Flex 4.1.  However, I was able to come up with a minimal set of files that does show the problem.  Slam.mxml is the same as before.  Global.mxml becomes:
    <?xml version="1.0" encoding="utf-8"?>
    <fx:Object xmlns:fx="http://ns.adobe.com/mxml/2009"
         xmlns:s="library://ns.adobe.com/flex/spark"
         xmlns:mx="library://ns.adobe.com/flex/mx">
         <fx:Script>
              <![CDATA[
                   public static var app:Slam = null;
                   public static const WIDGET_COLOR:uint = 0x987654;
                   public static var widgets:Widgets = new Widgets();
              ]]>
         </fx:Script>
    </fx:Object>
    and add an additional file, Widgets.as:
    package
         public class Widgets
             public function Widgets()
                  wColor = Global.WIDGET_COLOR;
             protected var wColor:int;
    This blows up with Global == null at the wColor initialization in Widgets.as.  I suspect there is some sort of chicken-and-egg issue going on here.  That Global isn't fully setup until it has initialized its widgets member, but initializing the widgets member needs Global fully setup.
    Moving the initialization of the widgets member to a separate Initialize function in Global, called from Slam.Initialize(), fixes the problem.

  • HOW-TO initialize class variable

    How can an annotation initialize a class variable? For example, JEE5 has an annotation called @EJB that initializes a class variable with a remote or local interface:
    @Stateless class Foo
    @EJB bar;
    bar.scoobyDoobyDoo(); // I can use bar seemingly before it was initialized!
    In general terms, how can annotation be used to initialize class variables?

    It can't.
    What it can do is tell something else that this needs to be done, and that something else can do it.
    That something else might be an annotation processor running at build / compile time, which might generate some code to do it, or might generate some configuration file that causes it to be done later.
    That something else might alternatively be a runtime artifact, that can look at the annotation and carry out the requested operation. For example a container could do it.
    So an annotation cannot do anything, including initailizing a class variable, but it can declare that the class variable needs to be initialized in some way.
    Bruce

  • Assign a value to class variable

    I want to define a class variable in class. And I want all subclasses of that class ot have a different value for that class variable. How can I do that?
    public class BaseClass {
      public static String tableName = "";
    }Now if I have a ClassA and I want to assign a value like this :
    public class ClassA extends BaseClass {
      tableName = "location";
    } I got an error message.
    I can move it in a static initializer block but then it will only work when the class is loaded. In my case its possible i want to get this value without loading the class.
    Ditto if i move it to constructor.
    Any input? Thanks

    Are you saying that if i have 2 classes ClassA and
    ClassB inherited from BaseClass, then both are
    sharing the same copy of 'tableName' staticvariable?
    If yes then I should go with an instance variable.No, I am saying that you can easily declare a
    tablName in A and another tableName in B.
    A.tableName will be shared between all the instances
    s of A. B.tableName will be shared between all the
    instances of B. And BaseClass.tableName is
    irelevant. I think you try to use
    BaseClass.tableName as some kind of template for
    sub-classes, but this does not happen: you need to
    declare tableName again and again in each subclass.
    IThanks for clarifying. Each class needs to have a variable "tableName" and it needs to have one copy of this variable for all of that class's objects. 2 classes will not have the same value of this tableName variable.
    Thats why I was defining it as static variable. And I define it in BaseClass so that I dont have to define it again in each subclass.
    Is there any better way? Thanks

  • Variable initialization

    Hello guys,
    Is there anybody know how and when java checks for variable initialization?For example if we change a value, assume a without initializing it we get variable a might not have been initialized.I wish to know how java checks that the variable is already assigned or not.
    int a;
    a++;//How java checks this
    regards,
    Haddock

    Rules is:
    To variables of instance - It's default value attribute automatically if not initialize with value.
    To local variable (methods for example) - It's default value in initialization has been MUST attributed
    Instance variables has a folliwing default value:
    class A{
    int i; //default value is 0
    char c; //default value is '\u0000'
    byte b; //default value is 0
    short s; //default value is 0
    long l; //default value is 0
    float f; //default value is 0.0
    double d; //default value is 0.0
    boolean bl; //default value is false
    String str; //Object is always null
    int x[]; // null. It's Object's array
    int x[5]; // 5 times default value 0.
    void testInitializeValue(){
    int x; // Compiler error; This variable has been initialized
    if(x == 5){
    return;
    Ok..Thanks!!

  • Private or Protected access for super class variables

    What is the best practice...
    Assume there is a class hierachy like
    Person (Super class) / StaffMember/ Professor (Sub class)
    1) The best way is to keep all the instance variables of each and every class private and access the private variables of super classes through subclass constructors (calling "super()")
    Ex:-
    public class Person {
    private String empNo;
    public Person (String empNo) {
    this.empNo = empNo;
    public class Professor extends Person {
    private String ........;
    private int ...........;
    public Professor (String pEmpNo) {
    super(pEmpNo);
    OR
    2)Changing the access level of the super class variables into "protected" or "default" and access them directly within the sub classes...
    Ex:-
    public class Person {
    protected String empNo;
    public Person () {
    public class Professor extends Person {
    String ........;
    int ...........;
    public Professor (String empNo) {
    this.empNo = empNo;
    Thank you...

    i'd think that you'd be better off relaying your initial values through the super class's constructor that way you'll get cleaner code, there's a possibly of inconsistency with option 2. i.e. you can then write code in your super classes to generally handle and properly initialize the instance variables while in the case of option 2, you'll have arbitrary constructors performing arbitrary initialization procedures

  • Class variable declaration

    Hello.
    Just looking through some code and I see a class variable declared as so...
    static final MessageDigest digestFunction;
    static { // The digest method is reused between instances to provide higher entropy.
            MessageDigest tmp;
            try {
                tmp = java.security.MessageDigest.getInstance(hashName);
            } catch (NoSuchAlgorithmException e) {
                tmp = null;
            digestFunction = tmp;
        }I have never come accoss a variable being declared in this way and it looks strange. The use of static before the opening brace is strange to me, and just the fact that this is not inside the constructor. Would this code be run after or before code inside the class constuctor?
    Thanks for any help, just a little confused!

    Sir_Dori wrote:
    Ah yes, of course it could not be within the constructor as it is static, sorry.
    So when would the class be loaded? Could this be the first time the ClassName.staticBlockVar is accessed, Most likely, yes. The first time something else uses the class. Classloading in Java is lazy.
    Also, is the code not reevaluated every time it is referenced ?No. Only when the class is loaded (actually, when it's initialized, but usually it boils down to the same thing)
    You can write some simple tests for this, by writing a constructor and a static initializer, then instantiating it twice, for example. Don't be afraid to just play around with code to test assumptions. I find JUnit very handy for experimenting with assumptions.

  • Unbound Class Variable Error

    Hi All,
    I am doing a webdynpro application. while deploying, it gives me an error
    "Unbound class Variable:'KMC_LIBS/bc.srf.framework_api.jar'.
    What is this error?
    Regards,
    Divya

    Hi,
    A Classpath Variable is just a variable which points to a directory in your file system.
    Useful when 1st developer has external jars on path1 and 2nd developer has external jars on path2 (the two paths are different) and the developers want to prevent classpath issues.
    In NWDS go to:
    Window -> Preferences -> Java -> Classpath Variables and check if 'KMC_LIBS' points to a directory.
    Also, you can delete this entry from your project's classpath and add the file 'bc.srf.framework_api.jar'' manually (without classpath variable).
    Regards,
    Omri

  • Create an instance of my class variable

    Hello all,
    I'm a newbie to iPhone/iPad programming and am having some trouble, I believe the issue is that I'm not creating an instance of my class variable.  I've got a class that has a setter and a getter, I know about properties but am using setters and getters for the time being.  I've created this class in a View-based application, when I build the program in XCode 3.2.6 everything builds fine.  When I step through the code with the debugger there are no errors but the setters are not storing any values and thus the getters are always returning 0 (it's returning an int value).  I've produced some of the code involved and I was hoping someone could point out to me where my issue is, and if I'm correct about not instantiating my variable, where I should do that.  Thanks so much in advance.
    <p>
    Selection.h
    @interface Selection : NSObject {
      int _choice;
    //Getters
    -(int) Choice;
    //Setters
    -(void) setChoice:(int) input;
    Selection.m
    #import "Selection.h"
    @implementation Selection
    //Getters
    -(int)Choice {
      return _choice;
    //Setter
    -(void)setChoice:(int)input{
              _choice = input;
    RockPaperScissorsViewController.m
    #import "RockPaperScissorsViewController.h"
    @implementation RockPaperScissorsViewController
    @synthesize rockButton, paperButton, scissorsButton, label;
    //@synthesize humanChoice, computerChoice;
    -(void)SetLabel:(NSString *)selection{
              label.text = selection;
    -(IBAction)rockButtonSelected {
    //          [self SetLabel:@"Rock"];
              [humanChoice setChoice:1];
    </p>
    So in the above code it's the [humanChoice setChoice:1] that is not working.  When I step through that portion with the debugger I get no errors but when I call humanChoice.Choice later on in the code I get a zero.
    -NifflerX

    It worked, thank you so much.  I put
    humanChoice = [[Selection alloc]init];
    In viewDidLoad and it worked like a charm.  Thank you again.
    -NifflerX

  • How to access the parent class variable or object in java

    Hi Gurus,
    I encounter an issue when try to refer to parent class variable or object instance in java.
    The issue is when the child class reside in different location from the parent class as shown below.
    - ClassA and ClassB are reside in xxx.oracle.apps.inv.mo.server;
    - Derived is reside in xxx.oracle.apps.inv.mo.server.test;
    Let say ClassA and ClassB are the base / seeded class and can not be modified. How can i refer to the variable or object instance of ClassA and ClassB inside Derived class.
    package xxx.oracle.apps.inv.mo.server;
    public class ClassA {
        public int i=10;
    package xxx.oracle.apps.inv.mo.server;
    public class ClassB extends ClassA{
        int i=20;   
    package xxx.oracle.apps.inv.mo.server.test;
    import xxx.oracle.apps.inv.mo.server.ClassA;
    import xxx.oracle.apps.inv.mo.server.ClassB;
    public class Derived extends ClassB {
        int i=30;
        public Derived() {
           System.out.println(this.i);                  // this will print 30
           System.out.println(((ClassB)this).i);  // error, but this will print 20 if Derived class located in the same location as ClassB
           System.out.println(((ClassA)this).i);  // error, but this will print 20 if Derived class located in the same location as ClassA
        public static void main(String[] args) { 
            Derived d = new Derived(); 
    Many thanks in advance,
    Fendy

    Hi ,
    You cannot  access the controller attribute instead create an instance of the controller class and access the attribute in the set method
    OR create a static method X in the controller class and store the value in that method. and you can access the attribute by 
    Call method class=>X
    OR if the attribute is static you can access by classname=>attribute.
    Regards,
    Gangadhar.S
    Edited by: gangadhar rao on Mar 10, 2011 6:56 AM

  • How to access class variables in anonymous class??.

    I have a boolean class level variable. Fom a button action , this boolean will set to true and then it used in anonymous class. In anonymous class, I am getting default value instead of true. Could u anyone help in this plzzz.

    first of all, you don't want parent because that is something that Containers use to remember their containment hierarchy. you are thinking of super which is also incorrect, because that has to do with inheritance.
    the problem here is a scoping problem. you generally would use final if you were accessing variables in an anonymous class that are in the local scope. in this case, you just need to create some test code and play with it. snip the code below and play with it. it shows both the given examples and some additional ways to change/display class variables.
    good luck, hackerx
    import javax.swing.*;
    import java.awt.event.*;
    public class Foo extends JPanel
         private boolean the_b = true;
         public static void main(String[] args)
              Foo f = new Foo();
              JFrame frame = new JFrame();
              frame.getContentPane().add(f);
              frame.pack();
              frame.show();
         public Foo()
              // get your button
              JButton b = new JButton("Not!");
              b.addActionListener(new ActionListener()
                   public void actionPerformed(ActionEvent ae)
                        // *** uncomment these to play around ***
                        // Foo.this.the_b = false; // this will work, but unnecessary
                        // the_b = false; // this works fine too
                        notFoo();
              this.add(b);
              // something to show the value that accesses a class variable
              // using an inner class instead of final nonsense
              DisplayThread t = new DisplayThread();
              t.start();
         private void notFoo()
              the_b = !the_b;
         class DisplayThread extends Thread
              public void run()
                   while(true)
                        System.err.println("boolean value: " + the_b);
                        try {
                        sleep(1000);
                        } catch(InterruptedException ie) {}
    }

  • WLS 10.0 Mp1 - Weblogic startup class to initialize client's SSL channels

    Hi,
    Is it possible to use Weblogic startup class to initialize client's SSL channels?
    Any pointers are appreciated.
    Thanks in advance.

    Hey
    If possible can you explain the issue in detail.
    What do you mean by “initialize client's SSL channels”
    Regards,
    Hussain

  • Static class variable

    Folks:
    I am little confused by static class variables in Java. Since Java doesn't have global varaibles it uses static variables instead. Please take a look at the following code and please tell me what goes wrong.
    /********** CONTENT OF Stack.java ***********/
    import java.util.Stack;
    public class StackClass
    {   static  Stack stack = new Stack (); }
    /********** CONTENT OF Test1 .java ***********/
    public class Test1
    public static void main( String[] args )
    StackClass.stack.push("Hello World");
    /********** CONTENT OF Test2.java ***********/
    public class Test2
    public static void main( String[] args )
    System.out.println( "Top on stack is " + StackClass.stack.peek() );
    I execute the above programs in the sequence of StackClass.java, Test1.java and Test2.java. I think in Test1.java after I push one element to the stack it should still be in the stack in Test2.java But I got :
    java.util.EmptyStackException
         at java.util.Stack.peek(Unknown Source)
         at Test2.main(Test2.java:16)
    Exception in thread "main"
    Can anybody give me a hint?
    Thanks a lot !

    After you run StackClass, the JVM (java.exe) ends and all the classes are unloaded including StackClass
    When you run Test1, StackClass is loaded, an item is pushed on the stack, and then the JVM exits and all classes are unloaded including StackClass
    When you run Test2, StackClass is loaded, and you get an error because the StackClass which was just loaded has no items in it.

  • Thread cannot access the class variables.

    Hi
    I have below code snippet : (Only section of which I have copied below)
    public class ProcessAppendAction extends HttpServlet implements Runnable{
         public ProcessAppendAction ()
    MI_OS_APPEND port ;
    protected void doGet(
              HttpServletRequest request,
              HttpServletResponse response)
              throws ServletException, IOException {
              //TODO : Implement
    port =
                        (MI_OS_APPEND) obj.getLogicalPort(
                             "MI_OS_APPENDPort",
                             MI_OS_APPEND.class);
    Thread[] threads = new Thread[noOfThreads];
    ProcessAppendAction run = new ProcessAppendAction(req);
                                            Thread th = new Thread(run);
                                            threads[no] = th;          
                                  threads[no].start();
                                  threads[no].join();
    public ProcessAppendAction(DT_REQUEST_APPEND req) {
              this.requestObj = req;
              // TODO Auto-generated constructor stub
    public void run()
              try
                   DT_RESPONSE res = this.port.MI_OS_APPEND(requestObj);
                                  catch(Exception e)
                                       int ch=0;
                                       ch++;
              }     In above code I am successfully creating an object in line :
    port =
                        (MI_OS_APPEND) obj.getLogicalPort(
                             "MI_OS_APPENDPort",
                             MI_OS_APPEND.class);But when I am trying to access this port variable in run method it is giving null.
    Port in my code is a class variable.
    Is it the case that thread cannot access class variable !!

    money321 wrote:
    ok, I have removed join() from just after start().So that now the Servlet can return before the new Thread has finished. Is this what you want?
    First I did invoked all threads and then in second loop i invoked Join on all threads.I don't understand. Why do you need to join() all the threads since you only start one thread in this request. What am I missing?
    >
    Now, my problem.
    It was solved when I substituted the line
    ProcessAppendAction run = new ProcessAppendAction(req)
    with
    ProcessAppendAction run = new ProcessAppendAction(req,port);Of course. Instance variables in Servlet instances are a no-no so passing the 'port' though an instance variable is just wrong.
    >
    That is passes port alongwith req while creating thread object.
    But still if class variables are not thread safe, then it means if I pass object 1 to thread 1.
    And then try to pass object 2 to thread 2, it might be possibility that object 1 of thread 1 might be replaced by object 2.
    So, thread 1 will get an updated value object 2.Yep - that is why you should not use instance variables in Servlets and why they are not thread safe.
    >
    Which is not what I intend to do...:-)

  • Static class variable doesn't store ?

    Hi,
    I'm a beginner in java.
    I defined a static class variable (nodes) in th following code :
    public class MySOMapp extends javax.swing.JFrame {
         private static final long serialVersionUID = 1L;
         private static SOMTrainer trainer;
         private static SOMLattice lattice;
         private static SOMNode nodes;
         private static Hashtable nwordf; 
         public MySOMapp(String args[]) {
              SOMNode nodes = new SOMNode();          //.....But a method of this class, nodes comes null. methos definition :
    private void makesame() {I don't understand why the nodes is null in makesame method which is in the same class with nodes ?
    thanks,
    Yigit

A: static class variable doesn't store ?

thankyou. I solved the problem. But why static fields
are not good idea ? How can i get rid of these...Remove the static word :) Seriously, try to develop a technique to get swiftly out of the static main method. Like this:
class MyClass {
    MyClass() {
        // Your code here instead of in main method.
    public static void main(String[] args) {
        new MyClass();
}

thankyou. I solved the problem. But why static fields
are not good idea ? How can i get rid of these...Remove the static word :) Seriously, try to develop a technique to get swiftly out of the static main method. Like this:
class MyClass {
    MyClass() {
        // Your code here instead of in main method.
    public static void main(String[] args) {
        new MyClass();
}

Maybe you are looking for

  • After new update on 25 july 2015 my SD is not being supported

    Well after the recent update of my tab slate 7 my sd card is not recognized i have tried several card but it won't work please give me a solution 

  • Open Canon 6D, CR2 files in Elements 10

    I recently upgraded my camera to the Canon 6D. Took loads of great pictures only to find that when I tried to open them in Elements 10 the programme didn't support them!!! I've search and trolled through every forum I can find lookong for a solution,

  • Macbook pro 17' 2010 10.7.5 crashing on packaging

    I have an macbook pro 17' 2010 with i7 2.8 ghz, 8gb ram, as you can see it's a pretty powerful mac even though it's 2 years old but i figure the i7 is still up to-date on the processers. But when ever i run the indesign it always crash and slow the c

  • Jms.bridge.TemporaryResourceException

    Folks,           I would very grateful if anyone has seen this one:           I'm attempting to connect to a remote weblogic server, my bridge destination is configured (as best I can see, correctly, as its a clone of a working environment on another

  • User Exit for checking GI in work order

    Dear PP Gurus, When user is doing confirmation for production order, system should check whether GI has been completed for that confirmation quantity. If not, system should prompt for eror message that GI has not completed. Can anybody please tell th