your programing

정적 필드에 정적 방식으로 액세스해야하는 이유는 무엇입니까?

lovepro 2020. 12. 26. 16:19
반응형

정적 필드에 정적 방식으로 액세스해야하는 이유는 무엇입니까?


public enum MyUnits
{
    MILLSECONDS(1, "milliseconds"), SECONDS(2, "seconds"),MINUTES(3,"minutes"), HOURS(4, "hours");

    private MyUnits(int quantity, String units)
    {
        this.quantity = quantity;
        this.units = units;
    }

    private int quantity;
    private  String units;

 public String toString() 
 {
    return (quantity + " " + units);
 }

 public static void main(String[] args) 
 {
    for (MyUnits m : MyUnits.values())
    {
        System.out.println(m.MILLSECONDS);
        System.out.println(m.SECONDS);
        System.out.println(m.MINUTES);
        System.out.println(m.HOURS);
    }
 }
}

이것은 게시물을 언급하는 것입니다. 왜 내

System.out.println(m.MILLSECONDS);

경고 제공-정적 필드 MyUnits.MILLSECONDS는 정적 방식으로 액세스해야합니까? 감사.


정적 필드에 액세스 할 때 클래스 (또는이 경우 열거 형)에서 액세스해야하기 때문입니다. 에서와 같이

MyUnits.MILLISECONDS;

에서와 같이 인스턴스에 없음

m.MILLISECONDS;

편집 이유에 대한 질문을 해결하려면 : Java에서 무언가를으로 선언 static하면 객체가 아니라 클래스의 구성원이라고 말하는 것입니다 (따라서 하나만있는 이유). 따라서 특정 데이터 멤버가 클래스와 연결되어 있기 때문에 개체에서 액세스하는 것은 의미가 없습니다.


실제로 타당한 이유가 있습니다.
모호함 때문에 비 정적 액세스가 항상 작동하는 것은 아닙니다 .

두 개의 클래스 A와 B가 있다고 가정합니다. 후자는 A의 하위 클래스이며 이름이 같은 정적 필드입니다.

public class A {
    public static String VALUE = "Aaa";
}

public class B extends A {
    public static String VALUE = "Bbb";
}

정적 변수에 직접 액세스 :

A.VALUE (="Aaa")
B.VALUE (="Bbb")

인스턴스를 사용한 간접 액세스 (VALUE에 정적으로 액세스해야한다는 컴파일러 경고를 제공함) :

new B().VALUE (="Bbb")

지금까지 컴파일러는 어떤 정적 변수를 사용할지 추측 할 수 있습니다. 수퍼 클래스에있는 변수는 다소 멀고 논리적으로 보입니다.

이제 까다로운 지점까지 : 인터페이스도 정적 변수를 가질 수 있습니다.

public interface C {
    public static String VALUE = "Ccc";
}

public interface D {
    public static String VALUE = "Ddd";
}

B에서 정적 변수를 제거하고 다음 상황을 관찰 해 보겠습니다.

  • B implements C, D
  • B extends A implements C
  • B extends A implements C, D
  • B extends A implements C 어디 A implements D
  • B extends A implements C 어디 C extends D
  • ...

The statement new B().VALUE is now ambiguous, as the compiler cannot decide which static variable was meant, and will report it as an error:

error: reference to VALUE is ambiguous
both variable VALUE in C and variable VALUE in D match

And that's exactly the reason why static variables should be accessed in a static way.


Because ... it (MILLISECONDS) is a static field (hiding in an enumeration, but that's what it is) ... however it is being invoked upon an instance of the given type (but see below as this isn't really true1).

javac will "accept" that, but it should really be MyUnits.MILLISECONDS (or non-prefixed in the applicable scope).

1 Actually, javac "rewrites" the code to the preferred form -- if m happened to be null it would not throw an NPE at run-time -- it is never actually invoked upon the instance).

Happy coding.


I'm not really seeing how the question title fits in with the rest :-) More accurate and specialized titles increase the likely hood the question/answers can benefit other programmers.

ReferenceURL : https://stackoverflow.com/questions/5642834/why-should-the-static-field-be-accessed-in-a-static-way

반응형