开发者

what is shared variable in java [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.

Want to improve this question? Add details and clarify the problem by editing this post.

Closed 3 years ago.

Improve this question 开发者_开发技巧

is there any concept of shared variable in java and if it is what is it?


It depends on what you mean as you can "share variables" or rather "share data" in various ways. I take it that you're a beginner, so I'll make it brief. The short answer is yes, you can share variables and below are a couple of ways to do it.

Share data as arguments for parameters in functions

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"

Share data as attributes in a class

You can define a class with attributes, when you instantiate the class to an object (i.e. you "new" it) you can set the object's attributes and pass it around. Simple example is to have a parameter class:

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

You can use it in the following way:

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"


Use static keyword, example:

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

Everytime you call method getCount(), count value will increase by 1


If you want to share variables between 2 functions, you can use global variables or pass them with pointers.

Example with pointers:

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

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


Not sure what this question means. All public classes are shared, all variables can be shared if they accessible through public methods, etc.


In the VB sense, a static field in Java is shared by all instances of the class.

In the classical sense, Java has various RPC, service and database access mechanisms.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜