Understanding Static Variables and Methods
- Static variables and methods belong to the class itself, not to any specific instance.
- They are shared across all instances of the class.
Characteristics of Static Variables
- Shared Across Instances: Only one copy exists, shared by all instances.
- Class-Level Access: Accessed using the class name, not an instance.
- Memory Efficiency: Stored in a fixed location, reducing memory usage.
Characteristics of Static Methods
- No Instance Required: Can be called without creating an object.
- Access to Static Members: Can only directly access static variables and other static methods.
- Utility Functions: Often used for operations that don't depend on instance data.
- In Java, static variables and methods are declared using the static keyword.
- In Python, class variables (static variables) are defined outside the__init__method, and static methods are created using the @staticmethoddecorator.
Understanding Non-Static Variables and Methods
Non-static variables and methods are associated with specific instances of a class.
Characteristics of Non-Static Variables
- Instance-Specific: Each object has its own copy.
- Unique State: Used to store data unique to each instance.
- Accessed via Instances: Accessed through the object that owns them.
Characteristics of Non-Static Methods
- Instance Required: Must be called on an object.
- Access to Instance Data: Can access both static and non-static variables.
- Behavior Definition: Define the actions an object can perform.
- In Java, non-static variables and methods are the default.
- In Python, they are defined within the __init__ method or other instance methods, using selfto refer to the instance.
Key Differences Between Static and Non-Static
- Ownership:
- Static: Belongs to the class.
- Non-Static: Belongs to the instance.
- Access:
- Static: Accessed via the class name.
- Non-Static: Accessed via an instance.
- Memory:
- Static: Single copy shared by all instances.