Object Oriented Programming Concepts

Static and Final Keywords

In Object-Oriented Programming (OOP), the static and final (or their equivalents in different languages) keywords play a significant role in managing class properties and behaviors.

Static Keyword

The static keyword is used to create methods and variables that belong to the class, rather than any instance of the class. It is not tied to any particular instance, and is useful in constants, utility functions, or keeping a count.

Like a public notice board in a school. It's one board (static) where messages are posted for all students (instances).

  • Characteristics:

    • Class Level: Static methods and variables are class-level, meaning they are shared among all instances of the class.
    • Memory Efficiency: Reduces memory usage as static variables are not replicated across instances.
    • Usage: Commonly used for constants, utility functions, or to keep a count of instances.
  • Example in Java:

    class Car {
        static int numberOfCars;
        Car() {
            numberOfCars++;
        }
        static void displayTotalCars() {
            System.out.println("Total cars: " + numberOfCars);
        }
    }

Final Keyword

The final keyword in Java (or its equivalent in other languages) is used to restrict further modification. It can be applied to variables, methods, and classes. The final keyword make variables become constants, methods cannot be overridden, classes cannot be subclassed. It ensures immutability and integrity, prevents changing the value of variables, secures method implementation and preserves class structure.

Think of it like a non-erasable writing on a board. Once written (final), it can't be modified.

  • Characteristics:

    • Constant Variables: When applied to variables, they become constants.
    • Prevent Overriding: Final methods cannot be overridden by subclasses.
    • Prevent Inheritance: Final classes cannot be subclassed.
  • Example in Java:

    class Vehicle {
        final void displayType() {
            System.out.println("This is a Vehicle");
        }
    }
    class Car extends Vehicle {
        // This would raise an error
        // void displayType() { ... }
    }

Understanding static and final keywords in OOP helps in optimizing resource usage and securing the class behavior. While static allows for shared class-level fields and methods, final ensures immutability and integrity of classes, methods, or variables.