๐Finalization
๐จ The Final Frontier of Java Keywords ๐จ
The dynamic trio of final, finally, and finalize() serve unique purposes though they sound similar! Let's break it down:
The Immutable final ๐
final ๐๐ Rules of final:
final int MAX_VALUE = 100; // Constant
final public void print() { // Method
//...
}
final class Car { // Class
//...
}Declares immutable properties โ๐
Prevent overriding in subclasses ๐ซ
Commonly used for constants ๐
Key Benefits:
Avoid unintended changes ๐ โโ๏ธ
Enforce architectural rules ๐ฎ
Improved understandability ๐ก
The Unstoppable finally ๐ฅ
finally ๐ฅ๐ง Purpose of finally:
try {
// Exception prone code
}
catch (Exception e) {
// Handle exception
}
finally {
// Always executes after try/catch โ
} Guaranteed execution before method exit ๐
Commonly closes resources ๐๏ธ
Why use finally?
finally?Release external resources ๐๏ธ
Restore program state ๐พ
Critical code that must run โ
The Destructor finalize() ๐
finalize() ๐๐ When finalize() gets called:
protected void finalize() {
//Cleanup before garbage collection
super.finalize();
}Just before object is garbage collected ๐๏ธ
Rarely used nowadays
try-finallypreferred
Downsides offinalize():
finalize():Not guaranteed to run ๐คทโโ๏ธ
Causes performance issues ๐ฅ
Anti-pattern in most cases โ
So while they sound similar, each handles unique responsibilities!
Last updated
Was this helpful?