Overview
This lecture explains the static keyword in Java, its uses in memory management, and shows how to apply it to variables, methods, blocks, and nested classes.
Introduction to static Keyword in Java
- static is a reserved keyword in Java used for efficient memory management.
- Static members belong to the class itself, not to specific instances.
- Accessing static members does not require creating an instance of the class.
Static Variables
- Static variables are class-level variables shared by all instances of a class.
- Only static member variables can be created, not static local variables.
- Static variables and static blocks are executed in the order they appear in the class.
- Static variables can be accessed using the class name or any instance.
Static Blocks
- A static block is a block of code prefixed with static, used for static member initialization.
- Static blocks execute before the main() method runs.
- In Java versions above 1.6, static block code must be used with a main() method.
Static Methods
- Static methods are declared with the static keyword and are called on the class itself.
- Static methods can access and modify static variables but not non-static data members.
- The main() method is a typical static method.
- Static methods cannot use this or super keywords.
Static Nested Classes
- A static nested class is a class declared static within another class.
- Static nested classes can be instantiated without an outer class instance.
- They cannot access non-static members of the outer class directly.
Static vs Non-Static (Summary Table)
- Static members are accessed via class name; non-static via objects.
- Static fields have one memory allocation per class; non-static have separate copies per object.
- Static methods can't be overridden; non-static methods can be.
Key Terms & Definitions
- static — Keyword that makes a class member shared across all instances.
- static variable — A class-level variable shared by all objects of that class.
- static block — Code block for initializing static members, executed before main().
- static method — Class-level method accessed without creating an object.
- static nested class — A class within a class, declared static.
Action Items / Next Steps
- Review example Java programs using static variables, methods, blocks, and nested classes.
- Practice creating and accessing static members in sample classes.