1

I am positive this has probably been answered many many times but I do not know the words to search for to find the answer. So here is the question

I'm using java and I have

int my_var = 3;

thing.myListener(new Listener() {
    public void onStart(int posistion) {
            my_var <-- I want to get access to my_var
        }
    });

How do I get access to my_var inside the onStart function. Also what is this type of problem called? Thanks!

1
  • 1
    Besides, I and Oracle recommend you to rename your variable to myVar instead of the PHP styled, my_var. Commented Jan 20, 2012 at 9:37

2 Answers 2

3

You have to make it final. This is an anonymous inner class.

final int my_var = 3;
Sign up to request clarification or add additional context in comments.

2 Comments

Can you show your exact code? The approach should work for any type of object.
If you are working with eclipse, it suggests you do just that automatically.
-2

I would suggest using global variables. Here is an example:

A simple way to utilize "global" variables in Java is to define a class Global with the desired variables as static members of it:

    public class Global {
            public static int x = 37;
            public static String s = "aaa";
    }

Such members can be accessed by saying:

    public class test {
            public static void main(String args[])
            {
                    Global.x = Global.x + 100;
                    Global.s = "bbb";
            }
    }

Is that what you are looking for?

2 Comments

It's a terrible idea to have global variables. Only constants can be global. If you make variables global, you'll lose thread safety.
@AlexisK won't be too long before it breaks though :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.