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):
}
}
Reputation Points: 1014
Solved Threads: 446
Nearly a Senior Poster
Offline 3,258 posts
since Dec 2007