java中是否有任何共享变量的概念,如果它是什么?
问问题
10013 次
5 回答
1
这取决于您的意思,因为您可以通过各种方式“共享变量”或更确切地说“共享数据”。我认为你是一个初学者,所以我会简要介绍一下。简短的回答是肯定的,您可以共享变量,下面是几种方法。
共享数据作为函数中参数的参数
void funcB(int x) {
System.out.println(x);
// funcB prints out whatever it gets in its x parameter
}
void funcA() {
int myX = 123;
// declare myX and assign it with 123
funcB(myX);
// funcA calls funcB and gives it myX
// as an argument to funcB's x parameter
}
public static void main(String... args) {
funcA();
}
// Program will output: "123"
将数据作为类中的属性共享
您可以定义一个具有属性的类,当您将该类实例化为一个对象(即“新建”它)时,您可以设置对象的属性并将其传递。简单的例子是有一个参数类:
class Point {
public int x; // this is integer attribute x
public int y; // this is integer attribute y
}
您可以通过以下方式使用它:
private Point createPoint() {
Point p = new Point();
p.x = 1;
p.y = 2;
return p;
}
public static void main(String... args) {
Point myP = createPoint();
System.out.println(myP.x + ", " + myP.y);
}
// Program will output: "1, 2"
于 2009-11-08T12:31:14.340 回答
1
使用static
关键字,例如:
private static int count = 1;
public int getCount() {
return count ++;
}
每次调用方法getCount()
,count
值都会增加 1
于 2011-02-22T14:36:38.840 回答
0
如果要在 2 个函数之间共享变量,可以使用全局变量或使用指针传递它们。
带指针的示例:
public void start() {
ArrayList a = new ArrayList();
func(a);
}
private void func(ArrayList a)
{
a.add(new Object());
}
于 2009-11-08T09:49:58.783 回答
0
不知道这个问题是什么意思。所有公共类都是共享的,如果可以通过公共方法访问所有变量,则可以共享所有变量等。
于 2009-11-08T09:59:43.813 回答