首页  >  文章  >  Java  >  掌握Java中的final关键字:常量、不变性等等

掌握Java中的final关键字:常量、不变性等等

Barbara Streisand
Barbara Streisand原创
2024-10-18 16:11:03828浏览

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中的final关键字:常量、不变性等等的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn