-3

java中是否有任何共享变量的概念,如果它是什么?

4

5 回答 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 回答
0

VB 意义上,Java 中的静态字段由类的所有实例共享。

经典意义上,Java 具有各种 RPC、服务和数据库访问机制。

于 2009-11-08T10:12:51.467 回答