Static variables in anonymous classes ..

How can i access a static variable from an anonymous class ..
class A{
outerMeth(){
Interface anon=new Interface(){
static int i;
// how can i acess 'i' ..
thanx in advance ..

sorry .. not a valid question ..
static var are not allowed in anonymous/inner classes ..
sorry ..
ignore this one ..

Similar Messages

  • 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) {}
    }

  • To use a static variable in another class,but report NullPointerException

    when TableMain is running,I run testRecord so that let TableMain add a occur informatin and
    happened time in a row in TableMain,but when I run testRecord,java report a NullPointerException and I dont know how to solve this problem,thanks for helping me to check my code;(error report info is in end)
    import java.awt.event.*;
    import javax.swing.table.*;
    import java.io.*;
    public class TableMain extends JFrame{
    JTable table;
    static OwnModel model;
    String[] columnHeader={"occur","time"};
    class OwnModel extends DefaultTableModel{
    public OwnModel(Object[] columnNames,int numRows){
    super(columnNames,numRows);
    public boolean isCellEditable(int row,int column){
    return false;
    public TableMain(){
    model=new OwnModel(columnHeader,0);
    table=new JTable(model);
    JScrollPane scroll=new JScrollPane(table);
    JButton save=new JButton("save record");
    JButton delete=new JButton("delete record");
    JPanel buttons=new JPanel();
    buttons.add(save);
    buttons.add(delete);
    JLabel sign=new JLabel("occur record");
    Container cp=getContentPane();
    cp.add(BorderLayout.NORTH,sign);
    cp.add(BorderLayout.CENTER,scroll);
    cp.add(BorderLayout.SOUTH,buttons);
    this.setSize(300,500);
    this.setVisible(true);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    public static void main(String[] args){
    new TableMain();
    import java.util.Vector;
    import java.util.Calendar;
    import java.text.SimpleDateFormat;
    public class testRecord{
    public static void main(String[] args){
    SimpleDateFormat simpledf=new SimpleDateFormat("yyyy/MM/dd hh:mm:ss");
    String tableName="friends";
    Calendar occurtime=Calendar.getInstance();
    Vector record=new Vector();
    record.add("send 'desc' sql, "+"operated table is :"+tableName);
    record.add(simpledf.format(occurtime.getTime()));
    System.out.println("model is "+Guide.model);
    System.out.println("record is "+record);
    Guide.model.addRow(record);
    error report:
    model is null
    record is [send 'desc' sql,operated table is :friends, 2004/05/26 11:39:03]
    Exception in thread "main" java.lang.NullPointerException
    at testRecord.main(testRecord.java:14)

    but I just use this constructor once,never use twice
    with same jvm;I thinks my idea is not too very badIt's a public constructor (if I'm looking in the right
    place) - it could be called from anywhere. To
    intialize a static variable outside the declaration,
    use a static initializer:private static String whatever;static {
    whatever = "whatever";
    }Or simply (in this case):private static String whatever = "whatever";

  • How to read static variable defined java class from flex?

    This is a beginner question. If I use remoteClass to map a java class and a flex class, how can I access a static variable defined in java class from the flex code?
    Thanks!

    Static propeties are by default ignored in the blazeds for serialization. You can try using another global property in the java bean which maps to the value stored in the static property( Hopefully it should work)
    eg,
    public String instanceValue = ClassName.staticValue;
    Ref: http://livedocs.adobe.com/blazeds/1/blazeds_devguide/help.html?content=serialize_data_3.ht ml

  • Static variable is single for class or single for JVM

    Hello,
    I have doubt, static variable is single for class or single for JVM. as per my knowledge static variable is single for class, but suposse i have an web application (war of an application ) i deployed the application twice with different context, supose yahoo and yahoo1. but the ditrectory structure and classes are same, if i have a statc variable in
    a classof an application, if i change the static variable of one class of an application wether it will change the static value of the class of another application.
    Example
              yahoo -> web-inf ->      classes ->MainPackage->     MyStaticClass->     static int i=9;
              yahoo1 -> web-inf ->      classes ->MainPackage->     MyStaticClass->     static int i=6;
              if i change the static value i in yahoo application to i=5;
              at the same time if i access the value i in yahoo1 application what i will get (wether 5 or 6).
    Thanks.

    A static variable is 'single' in its class.
    A Class is 'single' in its ClassLoader.
    There can be many ClassLoaders per JVM.
    There can be many applications per JVM. Each one generally has its own ClassLoader.
    Ergo there can be many instances of a Class, and therefore many instances of its static data.

  • How to give different value to a static variable???

    Hi all:
    Is there any solution to set different values to a static variable???I had try two ways but all have errors!
    1.Way_1
    protected String tmp=null;
    protected void initSituation(int sayorpress)
    if (sayorpress==0)
    tmp = "string1";
    else if (sayorpress==1)
    tmp = "string2";
    protected static String RESOURCE_STRING = tmp; <---error
    Error:non-static variable tmp cannot be referenced from a static context
    2.Way_2
    protected void initSituation(int sayorpress)
    if (sayorpress==0)
    protected static String RESOURCE_STRING = "string1"; <---error
    else if (sayorpress==1)
    protected static String RESOURCE_STRING = "string2"; <---error
    Error:illegal start of expression at
    not an expression statement at
    Thank you very mich!!!

    Try this:
    protected static String RESOURCE_STRING = null;
    protected void initSituation(int sayorpress)
    if (sayorpress==0)
    yourClass.RESOURCE_STRING = "string1";
    else if (sayorpress==1)
    yourClass.RESOURCE_STRING = "string2";
    You cannot declare a static variable inside a method. But you can access a static variable thorugh your class.

  • How to reference a static variable before the static initializer runs

    I'm anything but new to Java. Nevertheless, one discovers something new ever' once n a while. (At least I think so; correct me if I'm wrong in this.)
    I've long thought it impossible to reference a static variable on a class without the class' static initializer running first. But I seem to have discovered a way:
    public class Foo  {
      public static final SumClass fooVar;  // by default initialized to null
      static  {
         fooVar = new SumClass();
    public class Bar  {
      public static final SumClass barVar;
      static  {
         barVar = Foo.fooVar;  // <<<--- set to null !
    }Warning: Speculation ahead.
    Normally the initial reference to Foo would cause Foo's class object to instantiate, initializing Foo's static variables, then running static{}. But apparently a static initializer cannot be triggered from within another static initializer. Can anyone confirm?
    How to fix/avoid: Obviously, one could avoid use of the static initializer. The illustration doesn't call for it.
    public class Foo  {
      public static final SumClass fooVar = new SumClass();  // either this ..
    public class Bar  {
      public static final SumClass barVar = Foo.fooVar;  // .. or this would prevent the problem
    }But there are times when you need to use it.
    So what's an elegant way to avoid the problem?

    DMF. wrote:
    jschell wrote:
    But there are times when you need to use it. I seriously doubt that.
    I would suppose that if one did "need" to use it it would only be once in ones entire professional career.Try an initializer that requires several statements. Josh Bloch illustrates one in an early chapter of Effective Java, IIRC.
    Another classic usage is for Singletons. You can make one look like a Monostate and avoid the annoying instance() invocation. Sure, it's not the only way, but it's a good one.
    What? You only encounter those once in a career? We must have very different careers. ;)
    So what's an elegant way to avoid the problem? Redesign. Not because it is elegant but rather to correct the error in the design.<pff> You have no idea what my design looks like; I just drew you a couple of stick figures.If it's dependent on such things as when a static initializer runs, it's poor. That's avoidable. Mentioning a case where such a dependency is used, that's irrelevant. It can be avoided. I know this is the point where you come up with a series of unfortunate coincidences that somehow dictate that you must use such a thing, but the very fact that you're pondering the problem with the design is a design problem. By definition.
    Besides, since what I was supposing to be a problem wasn't a problem, your "solution" isn't a solution. Is it?Well, you did ask the exact question "So what's an elegant way to avoid the problem?". If you didn't want it answered, you should have said so. I'm wondering if there could be any answer to that question that wouldn't cause you to respond in such a snippy manner. Your design is supposedly problematic, as evidenced by your question. I fail to see why the answer "re-design" is unacceptable. Maybe "change the way the Java runtime initializes classes" would have been better?
    This thread is bizarre. Why ask a question to which the only sane answer, you have already ruled out?

  • What is static variable.

    What is static variable. what is difference between  static variable and public variable?

    Static variables belong to the Class. Non-static variables belong to Class instances.
    Public variables can be accessed from outside of the Package. Non-public variables can only be accessed within the Package.
    So they are quite different thing. You can have Static variables, Public Static variables, and Private Static variables...

  • Using a static variable declared in an applet in another class

    Hi guys,
    I created an applet and i want to use one of the static variables declared in teh applet class in another class i have. however i get an error when i try to do that...
    in my Return2 class i try to call the variable infoPanel (declared as a static JPanel in myApplet...myApplet is set up like so:
    public class myApplet extends JApplet implements ActionListener, ListSelectionListener
    here are some of the lines causing a problem in the Return2 class:
    myApplet.infoPanel.removeAll();
    myApplet.infoPanel.add(functionForm2.smgframeold);
    myApplet.infoPanel.validate();
    myApplet.infoPanel.repaint();
    here are some of the errors i get
    dummy/Return2.java [211:1] package myApplet does not exist
    myApplet.infoPanel.removeAll();
    ^
    dummy/Return2.java [212:1] package myApplet does not exist
    myApplet.infoPanel.add(functionForm2.smgframeold);
    ^
    dummy/Return2.java [213:1] package myApplet does not exist
    myApplet.infoPanel.validate();
    ^
    dummy/Return2.java [214:1] package myApplet does not exist
    myApplet.infoPanel.repaint();
    ^
    please help! thanks :)

    I don't declare any packages though....i think it just doesn't recognize myApplet for some reason..
    other errors i got compiling are:
    dummy/Return2.java [82:1] cannot resolve symbol
    symbol : variable myApplet
    location: class Return2
    updateDesc.setString(3, myApplet.staticName);
    I Don't get why i'm getting this error cuase they worked fine when myApplet was a standalone application, not an applet.
    myApplet is in the same folder as Return2 and it compiles properly.

  • How can I write an instance of a class in a static variable

    Hi !
    I have an instance of a class
    Devisen dev = new Devisen();
    In an other class I have a static method and I need there the content of some variables from dev.
    public static void abc()
    { String text=dev.textfield.getText()
    I get the errormessage, that the I cannot use the Not-static variable dev in a static variable.
    I understand that I cannot reference to the class Devisen because Devisen is not static I so I had to reference to an instance. But an instance is the same as a class with static methodes. (I think so)
    Is there a possibility, if I am in a static method, to call the content of a JTextField of an instance of a class ?
    Thank you Wolfgang

    Hallo, here is more code for my problem:
    class Login {
       Devisen dev=new Devisen();
    class Devisen {
       JTextField field2;
       if (!Check.check_field2()) return; // if value not okay than return
    class Check {
       public static void check_field2()
         HOW TO GET THE CONTENT OF field2 HERE ?
    One solution ist to give the instance to the static function, with the keyword "this"
    if (!Check.check_field2(this)) return;and get the instance
    public static void check_field2(Devisen dev)BUT is that a problem for memory to give every method an instance of the class ? I have 50 fields to control and I dont want do give every check_method an instance of Devisen, if this is a problem for performance.
    Or do I only give the place where the existing instance is.
    Hmm...?
    Thank you Wolfgang

  • 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

  • Why Inner class cannot access static variables

    Why is it that inner class can use only static final variables of the outerclass, and not ordinary static variables of the outer class. "Yes the JLS sepcifies that only final static variables can be used inside an inner class, esp a non blank final variable". But why this restriction.
    Thanks.

    so what are final static variables treated as if they
    are not variables. So if the final static value is
    not loaded when the class is loaded how will the
    class know about the value.??The actual value wil be substituted for the name of a static final value at compile time. That's why you can use them in switch statements where you can't use any variable variable.
    This is something to watch out for, by the way, because if you use a public static final value from one class in another the actual value will be compiled into the using class, so if you change the value where it's defined the class using it will have the old value until it's recompiled.

  • Can't we declare a static variable inside a memberfunction of a class?

    Hi,
    class A{
    public void fun()
    static int i=10;
    can' we declare static variable in member function of class?
    Thanks,

    It is a common idiom in C and C++, but it is forbidden
    in Java because it adds hidden dependencies.
    The C way of writing a serial number generator:
    int generate() {
    static int n = 0;
    return n++;
    }Pure C has only global functions. So it needs inner
    static variables to help to hide the data. I've had
    lots of headaches trying to make C programs with inner
    static variables work correctly because they usually
    are hidden in cross-reference listings.
    The Java way:
    public static class SerialNumberGenerator() {
    private static int n = 0;
    public static int generate() {
    return n++;
    }The code above is as static as the C code given
    before, but it tries to be more explicit (no hidden
    variables).Hum... have you tried to compile your sample ?
    (And anyway, what the hell would a static class be used for ???)
    But perhaps you meant:
    public final class SerialNumberGenerator {
       private static int n = 0;
       public static int generate() {
          return n++;

  • Error on compile - non-static variable can not be referencedfrom static con

    Error on compile happening with addButton?
    Thanks
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.JButton;
    import javax.swing.JLabel;
    import javax.swing.JTextField;
    import javax.swing.JFrame;
    public class Log implements ActionListener {
    JButton addButton;
    public static void addComponentsToPane(Container pane) {
    pane.setLayout(new GridBagLayout());
    GridBagConstraints c = new GridBagConstraints();
         c.gridy = 3;
    c.gridx = 0;
         JLabel callsignLabel= new JLabel("Callsign");
    pane.add(callsignLabel, c);
         c.gridy = 3;
    c.gridx = 1;
         JLabel nameLabel= new JLabel("Name");
    pane.add(nameLabel, c);
         c.gridy = 3;
    c.gridx = 2;
         JLabel timeLabel= new JLabel("Time");
    pane.add(timeLabel, c);
         c.gridy = 3;
    c.gridx = 3;
         JLabel dateLabel= new JLabel("Date");
    pane.add(dateLabel, c);
         c.gridy = 3;
    c.gridx = 4;
         JLabel frequencyLabel= new JLabel("Freq ");
    pane.add(frequencyLabel, c);
         c.gridy = 3;
    c.gridx = 5;
         JLabel locationLabel = new JLabel("Country/State");
    pane.add(locationLabel, c);
    c.gridy = 5;
    c.gridx = 0;
         addButton = new JButton("Add");
    pane.add(addButton, c);
         addButton.addActionListener(this);

    Thank you for the reply
    I am new to Java
    What is wrong with the way it is coded?The error message tells you what's wrong: You're trying to reference a non-static variable from a static context.
    If you don't know what that means, then click the link I provided and look at the results from that google search. You might have to go through a few before you find a satisfactory explanation. And after you've done that, if you have specific questions about things you didn't understand there, please post again.

  • How to call a variable in another class????

    if i have two classes in a package. From one class, how do i get the value of one of the variable in the other class.
    For example;
    Class A have a variable call totalNum which have a value initialise.
    Class B wan to get the value variable totalNum in class A.
    So do i go abt calling it?
    Cheers

    For example;
    Class A have a variable call totalNum which have a
    value initialise.
    Class B wan to get the value variable totalNum in
    class A.Your explanation is far from clear. Is the variable in class A a field? If yes, is it a static field? Is it declared public, private, etc.?
    If you don't understand the above questions, you should do the following:
    1) Learn the basics of the Java language from the Java Tutorial and/or from an entry-level book: http://java.sun.com/docs/books/tutorial/
    2) Post future question in the New To Java Technology forum.

Maybe you are looking for

  • Half of my ard clients have gone rogue... (offline, sleeping, denied)

    I have 18 iMacs on a Windows Active Directory network. At the end of the last school year I could control and manage all 17 (one new one this summer). This year I can only control 8 of the 18. The other 10 say either: Offline, Sleeping, or Access Den

  • Ipod Touch 4th Generation Not Syncing

    Hi. I hope someone can help with this. I have a 4th Gen Ipod touch, purchased October 2010. I recently purchased new Windows 7 notebook, transferred itunes library to new device, no problems. At present, here is my issue: when trying to sync my ipod,

  • Tv series will not play in itunes

    Please can you tell me why a tv series that i purchased from itunes (Yes Priminister) will not play in itunes.  It was playing fine a couple of weeks ago.  I have checked i have the latest itunes and quicktime updates.

  • How can i make calculation in two file using two parameter

    how can i make calculation in two file using two parameter Solved! Go to Solution.

  • "My Music" app .. song name displayed in error

    Hi, I have a C1-01. I have stored some mp3s on the memory card, and I checked with an ID3 editor on my PC, they have their ID3 tags correct. But in the "My Music" app on the phone, when I go to "All Songs", many songs have their name displayed in err