Rumah >Java >javaTutorial >Menguasai Kata Kunci terakhir dalam Java: Pemalar, Ketidakbolehubahan dan Banyak Lagi
The final keyword is one of the most fundamental tools for creating constants and ensuring immutability in Java. However, it’s more than just declaring variables that can’t change. In this post, we’ll explore the key aspects of the final keyword in different contexts and its impact on variables, static fields, and constructors.
Using final with variables ensures that once a value is assigned, it cannot be changed later. Here's a quick breakdown:
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'; }
In the example above:
A static final variable must be initialized at the time of declaration or in a static block. Unlike instance variables, static final fields cannot be initialized in the constructor because:
static final int ID = 1; static final int DEPT; static { DEPT = 90; // Initialized in static block }
Since constructors are called when instances are created, and static variables are associated with the class (not instances), it’s not possible to initialize or modify them inside a constructor.
Static variables without final can be modified even inside constructors.
static int salary; // Default value 0 at class loading public FinalKeyword() { salary = 10; // Static variable modified in constructor }
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.
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 |
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!
Java Fundamentals
Array Interview Essentials
Java Memory Essentials
Collections Framework Essentials
Happy Coding!
Atas ialah kandungan terperinci Menguasai Kata Kunci terakhir dalam Java: Pemalar, Ketidakbolehubahan dan Banyak Lagi. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!