Access Variables in Other Java Classes

To access variables of other classes, you can utilize the following methods:

  1. – fluctuating
  2. retrieveVariable()
  3. assignVariable()
public class OtherClass {
    private int variable;

    public int getVariable() {
        return variable;
    }

    public void setVariable(int value) {
        variable = value;
    }
}

// 在另一个类中访问OtherClass的变量
public class AnotherClass {
    public void accessVariable() {
        OtherClass other = new OtherClass();
        int value = other.getVariable();
        other.setVariable(10);
    }
}
  1. variable of ClassName
public class OtherClass {
    public static int variable;
}

// 在另一个类中访问OtherClass的静态变量
public class AnotherClass {
    public void accessVariable() {
        int value = OtherClass.variable;
        OtherClass.variable = 10;
    }
}
  1. Object reference: If you create an object of a class in another class, you can directly access variables using the object reference, as long as the access modifier of the variable allows access by objects of that class.
public class OtherClass {
    public int variable;
}

// 在另一个类中访问OtherClass的变量
public class AnotherClass {
    public void accessVariable() {
        OtherClass other = new OtherClass();
        int value = other.variable;
        other.variable = 10;
    }
}

Regardless of the method used, you need to ensure that the access modifier of the variable allows access by other classes. If the variable is declared as private, you need to provide public access methods.

bannerAds