0
class Param implements Runnable {
int c;

public Param(int a, int b){
    c = a+b;
}

public void run(){
    // System.out.println(a); // <<<<----What I'm going to do. it's impossible. 
}

 }

public class ParamTest {
public static void main(String args[]){
    Runnable r = new ThreadParam(10,20);
    new Thread(r).start();  

}   
} 

In above code, How can I print the value of "a"? My goal is, when I call Runnable r = new ThreadParam(10,20) in main method, I want to print value of "a" --> 10 . Is this impossible? If I declare int a into run() method, the result of "a" is '0'. I want to the result "10". How can I do that?

ton1
  • 7,238
  • 18
  • 71
  • 126

2 Answers2

3

Local variables and parameters only exist inside the function that declared them.
You need to store it in a field in the class, just like you stored c.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • Declare `int a` into class? or method? then its result is 0. How can I print 10? – ton1 Dec 17 '13 at 19:51
  • @user3100921: You need to declare it in the class, then assign it in the constructor. `int a` in the class and `int a` in the constructor are two different and unrelated variables. – SLaks Dec 17 '13 at 19:52
2

Create another instance variable to hold the a value:

int a;

and in your constructor, copy it down:

this.a = a;

Then you can access it in another method.

rgettman
  • 176,041
  • 30
  • 275
  • 357