Rules for Instance Variables in Java:
Declaration and Scope:
- Declared inside a class but outside of methods, constructors, or blocks.
- The scope of instance variables is throughout the class, except in static methods.
Default Values:
- Instance variables are automatically initialized with default values if not explicitly initialized:
int,long,short,byte→0float,double→0.0char→'\u0000'boolean→false- Object references →
null
- Instance variables are automatically initialized with default values if not explicitly initialized:
Access Modifiers:
- Can have any access modifier (
public,private,protected, or default). - Use
privateto ensure encapsulation and provide access through getter and setter methods.
- Can have any access modifier (
Instance-Specific:
- Each instance of a class has its own copy of instance variables.
- Modifying an instance variable in one object does not affect the same variable in another object.
Cannot Be Declared Static:
- Instance variables cannot use the
staticmodifier. If you need shared values across all instances, usestaticvariables instead.
- Instance variables cannot use the
Access from Static Methods:
- Instance variables cannot be accessed directly within a static context (e.g., a static method). You must create an object instance to access them.
Final Instance Variables:
- If an instance variable is declared
final, it must be initialized either:- At the time of declaration, OR
- In every constructor of the class.
- If an instance variable is declared
Initialization Block:
- Instance variables can be initialized using an instance initialization block.
Shadowing:
- Local variables or method parameters with the same name as an instance variable shadow the instance variable. Use
thisto refer to the instance variable explicitly.
- Local variables or method parameters with the same name as an instance variable shadow the instance variable. Use
Comments
Post a Comment