-1

I tried to access a variable in the main class from another class. I don't know if it's possible but I need those variables. If there is a way please show me. This is the simple example.

public class A(){

      public static String status;

      public static void main(String [] args){

           Scanner s = new Scanner(System.in);
           System.out.println("Deadlock or no deadlock (y/n)");
           status = s.nextline();

           ......

}

Then I want to use this variable "status" in another class which implements a runnable (thread). If status is "y" then a particular block of codes (if/else) inside the run methon will executes.

Anyone point me how do I call the main class so I can access the variable status from my the runner class. Thanks.

Kaka
  • 37
  • 1
  • 7

2 Answers2

2

The field status in class A is public and static, so you can call it from wherever you like.

public class B {
    public void myMethod() {
        System.out.println("A's status is " + A.status);
    }
}

A point on terminology: A here is a class, which represents an object. main happens to be a method within that class A. So you'd say that status belongs to A, not to main.

James Cronen
  • 5,715
  • 2
  • 32
  • 52
  • Welcome to Stack Overflow! If this answer meets your needs, please click on the checkmark to the left of the answer to accept it. Thanks, and good lucK! – James Cronen May 10 '14 at 03:36
0

No java is pass by value not pass by reference. You could follow the example I'm linking and see if that helps though.link You could make it static and it would be usable that way but any operations on it would change when ever you perform any on it hence static.

Community
  • 1
  • 1
user3587554
  • 353
  • 1
  • 7