![](/img/trans.png)
[英]How to access the variable that is being set in onCreate method of another class?
[英]How to access a variable of method of an another class?
实际上,我正在开发一个项目,在该项目中我必须访问另一个 class 的方法的变量,并且在我的项目中面临类似的情况,我无法返回该值。 请任何人解决这个问题。
package com.company;
class aaa {
int num1;
public void val() { // data type can't be changed
num1 = 100;
}
}
class bbb {
public void Values() {
int num = 100;
}
}
public class Main extends bbb {
public static void main(String[] args) {
// write your code here
aaa obj1 = new aaa();
bbb abj2 = new bbb();
System.out.println(obj1.num1); // wants to print value 100 here but
//without returning value from the function
}
}
local
变量 num1 就是这样,局部的。 它是在方法中创建的,因此 scope 是该方法的。 您需要创建一个名为 num1 的 class 成员。 如果 num1 是公开的,您可以按照您想要的方式引用它。 如果成员是私有的,你需要一个吸气剂。 如果要返回值,则需要将signature
从void
更改为int
。
我不容忍任何这种命名,只是保持简单。
public class AAA {
private int num1;
public int getNum1() {
return num1;
}
}
obj1.getNum1();
一旦这个变量在方法 scope 中,这是不可能的。 做你需要的唯一方法是在 class scope 中创建一个变量。 我不会做这样的事情,而是将变量创建为私有的,并改为使用 get 和 set 方法。
package com.company;
class aaa{
public int num1;
public void val(){
num1 = 100;
}
}
class bbb{
public void Values(){
int num = 100;
}
}
public class Main extends bbb{
public static void main(String[] args) {
// write your code here
aaa obj1 = new aaa();
bbb abj2 = new bbb();
System.out.println(obj1.num1); // now the variable is in public access
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.