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:

ElementMeaning
static variableShared across all instances
static methodCan be called without creating an object
static blockExecutes once when class is loaded
static classUsed 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:

ElementMeaning
final variableValue cannot be reassigned
final methodCannot be overridden
final classCannot 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 all
  • final: 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:

  1. Create a Bank class with:

    • A static variable totalAccounts that increments every time a new account is created.
    • A final variable accountNumber initialized in the constructor.
  2. Create a Utility class with only:

    • static methods: add, subtract, etc.
    • Prove that you can use them without instantiating the class.
  3. Create a final class SecurityProtocol with a method validate().

  4. 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?