>  기사  >  Java  >  정적 키워드: 메서드의 정적 및 비정적 멤버에 액세스

정적 키워드: 메서드의 정적 및 비정적 멤버에 액세스

DDD
DDD원래의
2024-10-25 00:39:30830검색

Static Keyword: Accessing Static and Non-Static Members in Methods

이 게시물에서는 메서드가 정적 및 비정적 멤버와 상호 작용하는 방식정적 지역 변수가 그렇지 않은 이유에 중점을 둘 것입니다. 허용된. 이는 Java 개발자에게 일반적인 인터뷰 주제이자 중요한 개념입니다.

이 게시물은 이 시리즈의 이전 게시물에서 다룬 개념을 바탕으로 작성되었습니다. 정적 키워드를 처음 사용하는 경우 여기에서 논의된 주제를 자세히 살펴보기 전에 더 나은 기초를 위해 정적 블록 및 정적 변수를 확인하는 것이 좋습니다.


정적 메소드 및 멤버 개요

  • 정적 멤버(변수 또는 메소드)는 클래스의 인스턴스가 아닌 클래스에 속합니다.
  • 비정적 멤버는 특정 객체에 연결되어 있으며 각 인스턴스마다 고유합니다.

정적 메서드는 클래스 수준에서 작동하므로 인스턴스 멤버에 직접 액세스할 수 없습니다.


정적 및 비정적 액세스를 보여주는 프로그램:

package keywords.static_keyword;

public class StaticVariables {

    // Static and non-static variables
    static int idStatic = 1;  // Shared across all instances
    int id;                   // Unique to each instance
    String name;              // Unique to each instance

    // Static block – Runs once when the class is loaded
    static {
        displayStatic();  // Call to static method

        // Cannot access non-static method in static block
        display(); // --> Compilation error
    }

    // Constructor to initialize non-static variables
    public StaticVariables(String name) {
        this.id = ++idStatic;  // Increment static ID for every new instance
        this.name = name;
    }

    // Non-static method: Can access both static and non-static members
    void display() {
        System.out.println("Instance Method:");
        System.out.println("Static ID: " + idStatic + ", Instance ID: " +
        id + ", Name: " + name);
    }

    // Static method: Can only access static members directly
    static void displayStatic() {
        System.out.println("Static Method:");
        System.out.println("Static ID: " + idStatic);

        // Static local variables are not allowed
        static int localVar = 10; // --> Compilation error
    }

    public static void main(String[] args) {
        // Call static method directly
        displayStatic();

        // Create instances to access non-static methods
        StaticVariables obj1 = new StaticVariables("Object1");
        StaticVariables obj2 = new StaticVariables("Object2");

        // Access non-static methods through objects
        obj1.display();
        obj2.display();
    }
}

주요 개념 및 액세스 규칙

1. Java에서 정적 지역 변수가 허용되지 않는 이유는 무엇입니까?

Java는 메소드나 블록 내에서 정적 지역 변수를 허용하지 않습니다.

  • 이유:
    • 로컬 변수는 메소드의 스택 프레임에 속하며 메소드가 호출될 때 생성됩니다.
    • 그러나 정적 변수는 클래스 수준 멤버이며 전체 클래스 수명 주기에서 액세스할 수 있어야 합니다.
    • 메서드 내에서 정적 변수를 허용하면 메서드의 지역 변수가 메서드 실행과 관련된 수명이 짧기 때문에 모순이 발생할 수 있습니다.
package keywords.static_keyword;

public class StaticVariables {

    // Static and non-static variables
    static int idStatic = 1;  // Shared across all instances
    int id;                   // Unique to each instance
    String name;              // Unique to each instance

    // Static block – Runs once when the class is loaded
    static {
        displayStatic();  // Call to static method

        // Cannot access non-static method in static block
        display(); // --> Compilation error
    }

    // Constructor to initialize non-static variables
    public StaticVariables(String name) {
        this.id = ++idStatic;  // Increment static ID for every new instance
        this.name = name;
    }

    // Non-static method: Can access both static and non-static members
    void display() {
        System.out.println("Instance Method:");
        System.out.println("Static ID: " + idStatic + ", Instance ID: " +
        id + ", Name: " + name);
    }

    // Static method: Can only access static members directly
    static void displayStatic() {
        System.out.println("Static Method:");
        System.out.println("Static ID: " + idStatic);

        // Static local variables are not allowed
        static int localVar = 10; // --> Compilation error
    }

    public static void main(String[] args) {
        // Call static method directly
        displayStatic();

        // Create instances to access non-static methods
        StaticVariables obj1 = new StaticVariables("Object1");
        StaticVariables obj2 = new StaticVariables("Object2");

        // Access non-static methods through objects
        obj1.display();
        obj2.display();
    }
}

2. 정적 메소드

  • 정적 변수와 기타 정적 메소드에 직접 액세스할 수 있습니다.
  • 비정적 멤버에 직접 액세스할 수 없습니다(정적 컨텍스트에는 객체가 없기 때문에).

3. 비정적 방법

  • 정적 및 비정적 멤버 모두에 액세스할 수 있습니다.
  • 이러한 유연성은 비정적 메소드가 객체 인스턴스에 속해 클래스 수준 및 인스턴스 수준 데이터에 모두 액세스할 수 있기 때문에 존재합니다.

4. 정적 블록

  • JVM이 클래스를 로드할 때 한 번 실행됩니다.
  • 정적 메서드를 호출할 수 있지만 현재 사용 가능한 개체가 없으므로 비정적 메서드를 직접 호출할 수는 없습니다.

프로그램 출력

static void displayStatic() {
    static int localVar = 10; // --> Compilation error
}

규칙 요약

Context Access Static Members Access Non-Static Members Allow Static Local Variables?
Static Method Yes No No
Non-Static Method Yes Yes No
Static Block Yes No No
컨텍스트 정적 회원 액세스 비정적 멤버 액세스 정적 지역 변수를 허용하시겠습니까? 정적 메소드 예 아니요 아니요 비정적 방법 예 예 아니요 정적 블록 예 아니요 아니요

정적 메소드를 언제 사용해야 합니까?

  • 유틸리티 또는 도우미 함수: 예: Math.pow().
  • 인스턴스 데이터가 필요하지 않은 경우: 객체 상태와 무관한 작업.

결론

정적 메소드와 멤버는 Java의 필수 도구입니다. 주요 내용은 다음과 같습니다.

  • 정적 메서드는 클래스 수준에서 작동하며 정적 멤버에만 직접 액세스할 수 있습니다.
  • 비정적 메서드는 정적 및 비정적 멤버 모두에 액세스할 수 있습니다.
  • 정적 지역 변수는 메소드 범위와 정적 수명 간의 충돌로 인해 Java에서 허용되지 않습니다.

이러한 규칙을 이해하면 프로그램에서 정적 메서드를 효과적으로 사용할 수 있습니다.


관련 게시물

  • Java 기초

  • 어레이 인터뷰 필수

  • Java 메모리 필수

  • 컬렉션 프레임워크 필수

즐거운 코딩하세요!

위 내용은 정적 키워드: 메서드의 정적 및 비정적 멤버에 액세스의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.