Java の最後のキーワードをマスターする: 定数、不変性など

Barbara Streisand
リリース: 2024-10-18 16:11:03
オリジナル
854 人が閲覧しました

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

最後のキーワードは、Java で定数を作成し、不変性を確保するための最も基本的なツールの 1 つです。ただし、単に変更できない変数を宣言するだけではありません。この投稿では、さまざまなコンテキストでの 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 中国語 Web サイトの他の関連記事を参照してください。

ソース:dev.to
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
著者別の最新記事
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!