> Java > java지도 시간 > 본문

Java의 최종 키워드 마스터하기: 상수, 불변성 등

Barbara Streisand
풀어 주다: 2024-10-18 16:11:03
원래의
828명이 탐색했습니다.

Mastering the final Keyword in Java: Constants, Immutability, and More

final 키워드는 Java에서 상수를 생성하고 불변성을 보장하는 가장 기본적인 도구 중 하나입니다. 그러나 이는 단지 변경할 수 없는 변수를 선언하는 것 이상입니다. 이 게시물에서는 다양한 맥락에서 final 키워드의 주요 측면과 변수, 정적 필드 및 생성자에 미치는 영향을 살펴보겠습니다.

1. 변수를 이용한 최종

변수와 함께 final을 사용하면 값이 할당되면 나중에 변경할 수 없습니다. 간단한 분석은 다음과 같습니다.

  • 상수 명명 규칙: 대문자 이름을 사용합니다(예: COUNT).
  • 초기화 요구 사항: 선언이나 생성자
  • 에서 초기화해야 합니다.
  • 모든 생성자는 초기화해야 합니다: 생성자에서 초기화하는 경우 모든 생성자는 값을 할당해야 합니다.
  • 세터 없음: 최종 변수는 변경할 수 없으므로 최종 변수에 대해 세터를 생성할 수 없습니다.
final int COUNT;  
final char GENDER = 'F'; // Initialized at declaration

public FinalKeyword() {
  // Initialized in Constructor
  COUNT = 90;

  // This will give a compile error
  // once initialized during declaration, cannot be changed
  GENDER = 'M'; 
}
로그인 후 복사

위의 예에서:

  • COUNT는 선언 시 초기화되지 않습니다. 즉 생성자에서 초기화해야 합니다.
  • GENDER는 'F'로 초기화되며 다른 곳에서는 변경할 수 없습니다.

2. 정적 변수를 사용한 최종

정적 최종 변수선언 시 또는 정적 블록에서 초기화되어야 합니다. 인스턴스 변수와 달리 정적 최종 필드는 다음과 같은 이유로 생성자에서 초기화될 수 없습니다.

  • 정적 변수는 개별 인스턴스가 아닌 클래스에 속합니다.
  • Final은 불변성을 강화합니다. 즉, 해당 값은 인스턴스에 의해서도 수정될 수 없습니다.
static final int ID = 1;  
static final int DEPT;  

static {
    DEPT = 90; // Initialized in static block
}
로그인 후 복사

생성자에서 정적 최종 변수를 초기화할 수 없는 이유는 무엇입니까?

인스턴스가 생성될 때 생성자가 호출되고 정적 변수는 (인스턴스가 아님) 클래스와 연결되므로 생성자 내에서 초기화하거나 수정할 수 없습니다.


3. 정적 변수와 정적 최종 변수

final이 없는정적 변수는 생성자 내부에서도 수정할 수 있습니다.

static int salary; // Default value 0 at class loading

public FinalKeyword() {
    salary = 10; // Static variable modified in constructor
}
로그인 후 복사

Key Differences

  • Static variables are shared across instances and can be modified by any of them.
  • Static final variables are immutable and shared by all instances, ensuring they remain constant throughout the program.

4. Constructor Requirements for Final Variables

When a final variable is not initialized at the time of declaration, it must be initialized in all constructors to avoid a compile-time error.

public FinalKeyword() {
    COUNT = 90; // Initialized in default constructor
}

public FinalKeyword(int count) {
    COUNT = count; // Initialized in parameterized constructor
}
로그인 후 복사

If a constructor does not initialize a final variable, the compiler will throw an error, ensuring the value is always assigned exactly once.


4. Comparison of Final Keyword Usage in Methods and Classes

Usage Effect Example
Final Method Cannot be overridden in subclasses. public final void getType() in java.lang.Object
Final Class Cannot be inherited by any class. java.lang.String, java.lang.Math
  • Final Methods: A final method ensures that subclasses cannot override it, enforcing consistent behavior across all instances. This is useful for methods like getType() in Object, which ensures critical functionality is not altered.
  • Final Classes: Declaring a class as final (e.g., String or Math) ensures that no subclass can alter its behavior, maintaining data integrity and preventing misuse.

Conclusion

The final keyword is a powerful tool in Java to enforce immutability and prevent unintended modifications. It plays a crucial role in defining constants, ensuring class-level consistency, and making code easier to understand and maintain.

Stay tuned for other posts in this series, where we’ll cover more Java keywords in depth to help you master the nuances of the language!


Related Posts

  • Java Fundamentals

  • Array Interview Essentials

  • Java Memory Essentials

  • Collections Framework Essentials

Happy Coding!

위 내용은 Java의 최종 키워드 마스터하기: 상수, 불변성 등의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
저자별 최신 기사
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!