HOWTO · Java
Chamar uma variável a partir de outro método em Java
Este tutorial explica como chamar uma variável num outro método em Java
Neste tutorial, aprenderemos como podemos chamar uma variável a partir de outro método em Java. Depende do tipo da variável e do seu âmbito dentro da classe.
Chamar uma variável estática a um método estático dentro da mesma classe em Java
Uma variável que é estática e declarada na mesma classe pode ser acedida dentro do método main e de outros métodos. No exemplo abaixo, a variável val declarada dentro do âmbito do método main só está disponível dentro desse âmbito enquanto a variável estática y é acedida dentro do outro método estático.
Podemos aceder à variável de âmbito limitado para a passar para o método onde pretendemos aceder à variável.
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);
}
}
Resultado:
In Main where static variable y is: 4
Value of static variable y in a static method is : 4 and String passed is: Hello
Chamar uma variável estática a partir de um método não estático dentro da mesma classe em Java
A variável y é estática mas o método de acesso a ela é não estático. Assim, precisamos de criar uma instância da classe para aceder ao método e à variável não-estática 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);
}
}
Resultado:
In Main where static variable y is: 6 and x is: 2
Non static variable x is : 2 and static variable y is: 6