java*享变量是什么

问题描述:

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

+5

请说明你在说什么 – 2009-11-08 10:01:41

如果你想在2个函数之间共享变量,你可以使用全局变量或者用指针传递它们。

示例使用指针:

public void start() { 
    ArrayList a = new ArrayList(); 
    func(a); 
} 

private void func(ArrayList a) 
{ 
    a.add(new Object()); 
} 

不知道这个问题是什么意思。所有公共类都是共享的,如果可以通过公共方法访问所有变量,则可以共享。

+0

他们可以共享为受保护的只要调用方法可以访问它们,也可以调用private。 – Spoike 2009-11-08 12:34:18

VB sense中,Java中的static field由类的所有实例共享。

classical sense中,Java有各种RPC,服务和数据库访问机制。

这取决于你的意思,因为你可以用不同的方式“共享变量”或者说“共享数据”。我认为你是初学者,所以我简单介绍一下。 简短回答是的,你可以共享变量,下面是几种方法来做到这一点。一类

分享数据作为论据,在功能

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" 

共享数据的属性参数

您可以定义属性的类,当你实例化类的一个对象(即你“”它)你可以设置对象的属性并传递它。简单的例子是,有一个参数类:

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" 

使用static关键字,如:

class Point { 
    public int x; // this is integer attribute x 
    public int y; // this is integer attribute y 
} 

您可以通过以下方式来使用它

private static int count = 1; 
public int getCount() { 
     return count ++; 
    } 

每次ü调用方法getCount将( ),计数将继续+1