简体   繁体   English

如何在 android 工作室中从另一个 class 访问变量

[英]how to access variables of one class from another in android studio

hey guys i wanted to use the variables of lets say class 1 in method A() in the class2 i have tried the following嘿伙计们,我想在class2的方法A()中使用class 1的变量我尝试了以下

class1 obj = new class1();
obj.A();

but its throwing an error saying cannot resolve symbol A()但它抛出一个错误,说无法解析符号A()

Just declare your variables to be public:只需将您的变量声明为公开的:

  public int variable1;
  public int variable2;

  Class1() {
      this.variable1 = 400;
      this.variable2 = 600;
  }

Class1 obj = new Class1();
obj.variable1;

Or just make them private and add getters:或者只是将它们设为私有并添加吸气剂:

  private int variable1;
  private int variable2;

  Class1() {
    this.variable1 = 400;
    this.variable2 = 600;
  }

  public int getVariable1() {
     return this.variable1;
  }

  public int getVariable2() {
     return this.variable2;
  }

then然后

Class1 obj = new Class1();
obj.getVariable1()

you have to return that variable, like this:您必须返回该变量,如下所示:

class Class1 {
    public int A() {
        int a = 5 + 6;
        return a;
    }
}

You need to add this return statement: return a;您需要添加此返回语句: return a; at the end of A() function to return the value在 A() function 的末尾返回值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Android Studio:如何将变量从一个 java 文件保存到另一个文件 - Android Studio : How to keep variables from one java file to another 从另一个类Android Studio访问变量 - Accessing variables from another class Android Studio 从一个类到另一个类的静态变量的访问 - Access of static variables from one class to another 如何在Java(Android)中将变量的值从一个类调用到另一个类 - How to call the value of variables from one class to another in Java (Android) 在IntelliJ或Android Studio中进行重构时,如何将静态变量从类移动到另一个类? - How to move static variables from a class to another class when refactoring in IntelliJ or Android Studio? 如何从位于同一 android 项目的另一个文件夹中的另一个 class 访问变量? - How to access variables from another class that are in another folder of the same android project? 访问另一类中一个类的变量 - access variables of one class in another class 如何从一个类访问String到另一个? - How to access String from one class to another? 无法从Android Studio中的另一个类访问变量的更改值 - Unable to access changed value of variable from another class in android studio 如何从Java中的另一个类访问一个类的函数的变量 - How to access the variables of a function of a class from another class in Java
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM