Javaに共有変数の概念はありますか?それが何であるか?
10013 次
5 に答える
1
static
キーワードを使用します。例:
private static int count = 1;
public int getCount() {
return count ++;
}
method を呼び出すたびにgetCount()
、count
value が 1 ずつ増加します
于 2011-02-22T14:36:38.840 に答える
1
さまざまな方法で「変数を共有する」または「データを共有する」ことができるため、意味によって異なります。初心者だと思いますので、簡単に説明します。簡単な答えはyesです。変数を共有することができます。以下にいくつかの方法を示します。
関数のパラメーターの引数としてデータを共有する
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"
クラスの属性としてデータを共有する
属性を持つクラスを定義できます。クラスをオブジェクトにインスタンス化する (つまり、" new " する) と、オブジェクトの属性を設定して渡すことができます。簡単な例は、パラメーター クラスを持つことです。
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 に答える
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 に答える