Skip to content

Commit f270085

Browse files
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

File tree

1 file changed

+1
-1
lines changed

1 file changed

+1
-1
lines changed

Section16StaticFinal/src/static and final.txt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ classes, but they have different purposes:
3939
System.out.println("This is a final method");
4040
}
4141

42-
final class MyClass { // final class (cannot be subclassed)
42+
final class Package2.MyClass { // final class (cannot be subclassed)
4343
// Class implementation
4444
}
4545

0 commit comments

Comments
 (0)