Java의 다른 메서드에서 변수 호출

  1. Java의 동일한 클래스 내의 정적 메서드에서 정적 변수 호출
  2. Java의 동일한 클래스 내에서 비정적 메서드에서 정적 변수 호출
Java의 다른 메서드에서 변수 호출

이 자습서에서는 Java의 다른 메서드에서 변수를 호출하는 방법을 배웁니다. 변수의 유형과 클래스 내의 범위에 따라 다릅니다.

Java의 동일한 클래스 내의 정적 메서드에서 정적 변수 호출

정적이고 동일한 클래스에서 선언 된 변수는 기본 메서드 및 다른 메서드 내에서 액세스 할 수 있습니다. 아래 예에서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
튜토리얼이 마음에 드시나요? DelftStack을 구독하세요 YouTube에서 저희가 더 많은 고품질 비디오 가이드를 제작할 수 있도록 지원해주세요. 구독하다
작가: Rupam Yadav
Rupam Yadav avatar Rupam Yadav avatar

Rupam Saini is an android developer, who also works sometimes as a web developer., He likes to read books and write about various things.

LinkedIn

관련 문장 - Java Class

관련 문장 - Java Method