HOWTO · Java
Java で別のメソッドから変数を呼び出す
このチュートリアルでは、Java の別のメソッドで変数を呼び出す方法を説明します。
このチュートリアルでは、Java の別のメソッドから変数を呼び出す方法を学習します。これは、変数のタイプとクラス内のスコープに依存します。
Java で同じクラス内の静的メソッドから静的変数を呼び出す
同じクラス内で宣言された静的な変数は、main メソッドや他のメソッド内でアクセスすることができます。以下の例では、main メソッドのスコープ内で宣言された変数 val はそのスコープ内でのみ利用可能であり、静的変数 y は他の静的メソッド内でアクセス可能です。
スコープが制限された変数にアクセスして、その変数にアクセスしようとするメソッドに渡すことができます。
public class CallAVariable {
static int y = 4; // declared inside class scope.
public static void main(String[] args) {
String val = "Hello"; // declared inside the scope of main method hence available in main only.
System.out.println("In Main where static variable y is: " + y);
callInNormal(val);
}
public static void callInNormal(String val) {
System.out.println("Value of static variable y in a static method is : " + y
+ " and String passed is: " + val);
}
}
出力:
In Main where static variable y is: 4
Value of static variable y in a static method is : 4 and String passed is: Hello
Java の同じクラス内の非静的メソッドから静的変数を呼び出す
変数 y は静的ですが、それにアクセスするメソッドは非静的です。したがって、メソッドと非静的変数 x にアクセスするためにクラスのインスタンスを作成する必要があります。
public class CallAVariable {
int x = 2;
static int y = 6;
public static void main(String[] args) {
// since the method is non static it needs to be called on the instance of class.
// and so does the variable x.
CallAVariable i = new CallAVariable();
System.out.println("In Main where static variable y is: " + y + " and x is: " + i.x);
i.callInNormal(i.x);
}
public void callInNormal(int x) {
CallAVariable i = new CallAVariable();
System.out.println("Non static variable x is : " + x + " and static variable y is: " + y);
}
}
出力:
In Main where static variable y is: 6 and x is: 2
Non static variable x is : 2 and static variable y is: 6