在 Java 中调用另一个方法中的变量

在 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

Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe