Commit f270085
committed
feat: Document differences between static and final keywords in Java with variables, methods, and classes
WHAT the doc covers:
- **static keyword**
- Applies to: variables, methods, inner classes, and blocks.
- Purpose: binds the member to the class rather than to any specific object.
- Behavior:
- Static variables: shared across all instances of the class.
- Static methods: callable without object creation; can only access static members.
- Static blocks: executed once when the class is loaded, often used for initialization.
- Example:
```java
class Example {
static int count = 0; // shared across all instances
static void increment() { // can be called as Example.increment()
count++;
}
}
```
- **final keyword**
- Applies to: variables, methods, and classes.
- Purpose: makes something immutable or non-overridable.
- Behavior:
- Final variable: value cannot be reassigned once initialized.
- Final method: cannot be overridden by subclasses.
- Final class: cannot be extended.
- Example:
```java
final int MAX_VALUE = 100; // constant
final void show() { // cannot be overridden
System.out.println("Final method");
}
final class MyClass { // cannot be subclassed
// implementation
}
```
WHY this matters:
- `static` controls **scope and lifetime**, allowing memory-efficient shared state and utility methods.
- `final` enforces **immutability and stability**, preventing accidental changes, ensuring contracts, and increasing program safety.
- Both keywords are fundamental in designing reliable APIs, constants, utility classes, and secure inheritance hierarchies.
DIFFERENCES (key interview points):
1. **Purpose**:
- `static`: member belongs to the class itself.
- `final`: member cannot be changed/overridden/extended.
2. **Variables**:
- `static`: one shared copy for all objects.
- `final`: once assigned, cannot be reassigned.
3. **Methods**:
- `static`: invoked without an object; cannot use `this` or access instance members.
- `final`: cannot be overridden in subclasses.
4. **Classes**:
- `static`: denotes nested static class (accessed without outer instance).
- `final`: class cannot be subclassed.
Short key: java static-vs-final variables methods classes immutability class-level-members.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent 1e054ce commit f270085
1 file changed
+1
-1
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
39 | 39 | | |
40 | 40 | | |
41 | 41 | | |
42 | | - | |
| 42 | + | |
43 | 43 | | |
44 | 44 | | |
45 | 45 | | |
| |||
0 commit comments