954,518 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

accessing variables from a void method in one file and using it in another

I have two .java files and I want to access a variable of a method in one of the files and use it in another. However, I dont want to call the whole method and I dont want the method to return a value...I'll try to illustrate below

//file_A.java
class file_A{
//some code 
  void first_method(){
      int variable_a=2; //variable used in this method for several things
  }
}

//file_B.java
class file_B
{
//some code
  void second_method(){
      System.out.println("var"+variable_a);//ofcourse this does not work but Iam trying to do something like this
  }
}

I hope this helps to explain my problem

joshmo
Posting Whiz in Training
280 posts since Oct 2007
Reputation Points: 19
Solved Threads: 20
 

You can have the variable be "global". Here are 2 examples:

class ClassA {
public int variableA = 0;

public ClassA() {

}

public void method() {
   variableA = 2;
}
}
class ClassB {
public ClassB() {

}

public void methodB() {
  ClassA clA = new ClassA();
  clA.method();

  System.out.println(clA.variableA ):
}
}


If you have a variable declared in a method you cannot access it from outside that method because it is out of scope. You need to declare it inside the class. If you declare it "private" you will need a "get" method in order to return its value.
Now if you want to access it from another class you will need of course to create an instance of the class: "ClassA" and call the method that changes its value.

But things are different when you declare it static:

class ClassA {
public static int variableA = 0;

public static void method() {
   variableA = 2;
}
}
class ClassB {
public ClassB() {

}

public void methodB() {
  ClassA.method();

  System.out.println(ClassA.variableA):
}
}
javaAddict
Nearly a Senior Poster
Team Colleague
3,329 posts since Dec 2007
Reputation Points: 1,014
Solved Threads: 448
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You