development

Java에 상수 기능이없는 이유는 무엇입니까?

big-blog 2020. 6. 27. 10:09
반응형

Java에 상수 기능이없는 이유는 무엇입니까?


Java에서 상수 뒤에있는 이유를 찾으려고 노력하고 있었는데 Java를 사용하여 final키워드 를 사용하여 상수를 선언 할 수 있음을 알게되었습니다 .

내 질문은 Java가 상수 ( const) 기능을 도입하지 않은 이유 입니다. 많은 사람들이 C ++에서 왔다고 말하고 있으므로 C ++에는 const키워드가 있습니다.

당신의 생각을 공유하십시오.


무거운 C ++ 코딩에서 Java로 갈 때마다 Java의 const-correctness 부족에 적응하는 데 약간의 시간이 걸립니다 . constC ++ 에서이 사용법은 모르는 경우 상수 변수를 선언하는 것과 크게 다릅니다. 본질적으로 const 포인터라는 특수한 포인터를 통해 액세스 할 때 객체를 변경할 수 없도록합니다 .Java에서는 일반적으로 const 포인터를 반환하려는 곳에서 대신 인터페이스 유형으로 참조를 반환합니다 부작용이 없어야하는 메소드 만 포함합니다. 불행히도, 이것은 언어에 의해 시행되지 않습니다.

Wikipedia는 주제에 대해 다음 정보를 제공합니다.

흥미롭게도 Java 언어 사양은 const를 예약 키워드 (예 : 변수 식별자로 사용할 수없는 키워드)로 간주하지만 의미를 할당하지 않습니다. 키워드의 예약은 Java 언어의 확장이 C ++ 스타일 const 메소드 및 const 유형에 대한 포인터를 포함 할 수 있도록하기 위해 발생했다고 생각됩니다. Java에서 프로세스 정확성을 구현하기위한 Java 커뮤니티 프로세스의 개선 요청 티켓은 2005 년에 닫혔으며 이는 const 정확성이 공식 Java 스펙에 절대 영향을 미치지 않을 것임을 암시합니다.


무엇을 const의미
첫째, 실현을하는 "CONST"의 의미 키워드 수단 다른 사람들에게 여러 가지를 :

  • 읽기 전용 참조 -Java final의미론-참조 변수 자체는 다른 인스턴스 (메모리 위치)를 가리 키도록 재 할당 할 수 없지만 인스턴스 자체는 수정할 수 있습니다
  • 읽기 전용 참조 -C const포인터 / 참조 시맨틱-이 참조는 인스턴스를 수정하는 데 사용할 수 없음을 의미합니다 (예 : 인스턴스 변수에 할당 할 수없고 변경 가능한 메소드를 호출 할 수 없음)-참조 변수에만 영향을 미치므로 동일한 인스턴스가 인스턴스를 수정할 수 있습니다
  • 불변 객체 -인스턴스 자체를 수정할 수 없음을 의미-인스턴스에 적용되므로 비 const 참조는 허용되지 않거나 인스턴스를 수정하는 데 사용할 수 없습니다
  • 위의 일부 조합 ?
  • 다른 사람 ?

왜 또는 왜const
두 번째가 아닌지, "pro"대 "con"인수 중 일부를 실제로 조사하려면이 개선 요청 (RFE) "버그"아래의 토론을 참조하십시오. 이 RFE는 "읽기 전용 참조"유형 "const"기능을 요청합니다. 1999 년에 문을 연 후 2005 년에 Sun에 의해 폐쇄 / 거부 된 "const"주제는 다음과 같이 활발하게 논의되었습니다.

http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4211070

양쪽에 좋은 주장이 많이 있지만, 자주 제기되는 (반드시 설득력이 있거나 분명하지 않은) 이유는 const다음 같습니다.

  • 남용 및 / 또는 오용 될 수 혼란 의미를 가질 수있다 (투시 무엇 const평균 위)
  • 사용 가능한 기능을 복제 할 수 있음 (예 : 불변 인터페이스를 사용하여 불변 클래스 설계)
  • 특징적인 크리프가 발생하여 값으로 객체를 전달하는 것과 같은 다른 의미 적 변경이 필요할 수 있습니다.

이것이 좋은 이유인지 나쁜 이유인지에 대해 누군가 토론하기 전에, 이것이 나의 이유아니라는 점에 유의하십시오 . 그것들은 내가 RFE 토론을 감추지 않고 얻은 몇 가지 이유의 "장점"입니다. 나는 그들 자신에 반드시 동의하지는 않습니다.-나는 왜 일부 사람들 (내가 아닌)이 const키워드가 좋은 생각이 아닐 수 있다고 느끼는지 인용하려고합니다 . 개인적으로, 나는 더 많은 "const"의미를 모호하지 않은 방식으로 언어에 도입하기를 원합니다.


const C ++에서 값이 상수라는 의미는 아닙니다.

const C ++에서 계약의 클라이언트는 그 가치를 변경하지 않을 것을 암시합니다.

const스레드 기반 동시성을 지원하는 환경에 있으면 식 의 값이 변경 되는지 여부 가 더 분명해집니다.

Java는 처음부터 스레드 및 잠금 동시성을 지원하도록 설계되었으므로 의미를 갖도록 용어를 오버로드하여 혼란을 가중시키지 않았습니다 final.

예 :

#include <iostream>

int main ()
{
    volatile const int x = 42;

    std::cout << x << std::endl;

    *const_cast<int*>(&x) = 7;

    std::cout << x << std::endl;

    return 0;
}

출력 42와 7.

Const가 아닌 별칭이 만들어지면서로 x표시 되었지만 상수는 아닙니다. 모든 컴파일러 가이 동작에 필요한 것은 아닙니다 (모든 컴파일러가 상수를 인라인하도록 허용되어 있음)constxvolatile

With more complicated systems you get const/non-const aliases without use of const_cast, so getting into the habit of thinking that const means something won't change becomes more and more dangerous. const merely means that your code can't change it without a cast, not that the value is constant.


This is a bit of an old question, but I thought I would contribute my 2 cents anyway since this thread came up in conversation today.

This doesn't exactly answer why is there no const? but how to make your classes immutable. (Unfortunately I have not enough reputation yet to post as a comment to the accepted answer)

The way to guarantee immutability on an object is to design your classes more carefully to be immutable. This requires a bit more care than a mutable class.

This goes back to Josh Bloch's Effective Java Item 15 - Minimize Mutability. If you haven't read the book, pick up a copy and read it over a few times I guarantee it will up your figurative "java game".

In item 15 Bloch suggest that you should limit the mutability of classes to ensure the object's state.

To quote the book directly:

An immutable class is simply a class whose instances cannot be modified. All of the information contained in each instance is provided when it is created and is fixed for the lifetime of the object. The Java platform libraries contain many immutable classes, including String, the boxed primitive classes, and BigInte- ger and BigDecimal. There are many good reasons for this: Immutable classes are easier to design, implement, and use than mutable classes. They are less prone to error and are more secure.

Bloch then describes how to make your classes immutable, by following 5 simple rules:

  1. Don’t provide any methods that modify the object’s state (i.e., setters, aka mutators)
  2. Ensure that the class can’t be extended (this means declaring the class itself as final).
  3. Make all fields final.
  4. Make all fields private.
  5. Ensure exclusive access to any mutable components. (by making defensive copies of the objects)

For more details I highly recommend picking up a copy of the book.


The C++ semantics of const are very different from Java final. If the designers had used const it would have been unnecessarily confusing.

The fact that const is a reserved word suggests that the designers had ideas for implementing const, but they have since decided against it; see this closed bug. The stated reasons include that adding support for C++ style const would cause compatibility problems.


There is a way to create "const" variables in Java, but only for specific classes. Just define a class with final properties and subclass it. Then use the base class where you would want to use "const". Likewise, if you need to use "const" methods, add them to the base class. The compiler will not allow you to modify what it thinks is the final methods of the base class, but it will read and call methods on the subclass.


There would be two ways to define constants - const and static final, with the exact same semantics. Furthermore static final describes the behaviour better than const


You can use static final to create something that works similar to Const, I have used this in the past.

protected static final int cOTHER = 0;
protected static final int cRPM = 1;
protected static final int cSPEED = 2;
protected static final int cTPS = 3;
protected int DataItemEnum = 0;

public static final int INVALID_PIN = -1;
public static final int LED_PIN = 0;

참고URL : https://stackoverflow.com/questions/2735736/why-is-there-no-constant-feature-in-java

반응형