开发者

How to access a variable from one function to another function in java ? Can that local variable be made static in a function? [duplicate]

This question already has answers here: Closed 12 years ago.

Possible Duplicate:

How do I create a static local variable in Java?

Hi I am noob to java I wanna access local variable of a function in another function. But java does java support static variable in a function? If not then how to access that variable.I do not want to make th开发者_StackOverflowat local variable as instance variable of calss.

Thanks


Maybe I'm totally wrong but the task sounds to me like a part of closures concept (even if authod didn't mean anything related).

So, java way is:

public void foo () {
   final SomeClass obj = new SomeClass ();
   Bar b = new Bar () {
      public void bar () {
         obj.doSmth ();
      }
   };
}

Of course, this concrete code is just an unuseful example.


In the declaration of your method where you need to access the variable, include it as a parameter.

public int myMethod(int i){
    System.out.println(i);
}

And then pass the variable to that method as a parameter.

public static void main(String [] args){
    int myInt = 5;
    myMethod(myInt);
}


  1. In Java you say "method" instead of "function".

  2. What do you mean by "static variable in a function"? If you mean C/C++ style static local variable, then you have to use class or instance variable, depending on your needs.

  3. "Local" means that something cannot be accessed outside it's scope. So you can't access method's local variable from outside of the method body, just by definition.

  4. And why can't you use class or instance variable?


It depends but there are a few ways.

If you're in the same object you could use a normal member variable, if you're calling between objects you could just provide getters and setters for that variable. Alternately if the two methods are related just provide the value as a parameter.

When you talk about between one function and another function it's not clear whether you mean methods in the same class or between different classes. Maybe if you're thinking about functions in Java and not thinking about classes, objects and methods, you would find it useful to go over the basic object orientation stuff as well. I know I had that problem often when I was making the transition from procedural to object-oriented programming. It's a while ago now, but this series of tutorials helped me a lot with that.


No you cannot declare a static variable in a method in java.

and you can not access a variable from one method in another method. rather if it is an object you can send its reference to other method through a method call. and if its a primitive then you can send its value.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜