[英]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.