Static and Final modifiers
Letβs tackle two foundational modifiers in Java that have a huge impact on memory management, immutability, and class behavior: static
and final
.
π© Java Core Concept: static
and final
Keywords
1οΈβ£ static
Keyword β Belongs to the Class, Not the Object
π§ What it does:
When you declare something as static
, it becomes class-level β not tied to any individual object.
β
Use Cases of static
:
Element | Meaning |
---|---|
static variable | Shared across all instances |
static method | Can be called without creating an object |
static block | Executes once when class is loaded |
static class | Used for nested classes only |
π¦ Example: Static Variable & Method
class Counter {
static int count = 0; // Shared by all objects
Counter() {
count++; // Increment shared count
}
static void showCount() {
System.out.println("Objects created: " + count);
}
}
public class Main {
public static void main(String[] args) {
new Counter();
new Counter();
Counter.showCount(); // Outputs: 2
}
}
π― Why Use static
?
- Memory-efficient: One copy shared across all instances.
- Useful for utility methods (e.g.,
Math.sqrt()
,Collections.sort()
). - Implements constants (
static final
) that donβt change.
2οΈβ£ final
Keyword β Cannot Be Changed
π§ What it does:
When something is declared final
, it means it cannot be changed or overridden after it’s assigned or defined.
β
Use Cases of final
:
Element | Meaning |
---|---|
final variable | Value cannot be reassigned |
final method | Cannot be overridden |
final class | Cannot be subclassed |
π¦ Example: Final Variable
class Constants {
static final double PI = 3.14159; // Constant value
}
π¦ Example: Final Method
class Vehicle {
final void start() {
System.out.println("Vehicle is starting");
}
}
class Car extends Vehicle {
// Cannot override start() here
}
π¦ Example: Final Class
final class Calculator {
int add(int a, int b) {
return a + b;
}
}
// class AdvancedCalculator extends Calculator {} // β Error
π static final
Combo β Constant
class Config {
public static final String APP_NAME = "MyApp";
}
This is how Java defines constants:
static
: shared by allfinal
: value cannot change
π§ Why Use final
?
- Ensures immutability.
- Helps prevent accidental overrides or changes.
- Often used in security, constants, and thread-safety.
π§© Deeper Design Insight
static
relates to class-level design:
- Shared resources
- Singleton patterns
- Utility classes
final
supports immutability and safe OOP:
- Final variables = safe data
- Final methods/classes = control behavior
π Homework for Students
π Tasks:
Create a
Bank
class with:- A
static
variabletotalAccounts
that increments every time a new account is created. - A
final
variableaccountNumber
initialized in the constructor.
- A
Create a
Utility
class with only:static
methods:add
,subtract
, etc.- Prove that you can use them without instantiating the class.
Create a
final
classSecurityProtocol
with a methodvalidate()
.Try overriding a
final
method in a subclass. Document the compiler error.
Ready to move into Exception Handling, or should we continue with keywords like this
, super
, or access control like public/private/protected
in depth?