Junior
What is the difference between an instance member of a class and a static member of a class?
sobes.tech AI
Answer from AI
An instance member belongs to a specific object of the class, while a static member belongs to the class itself.
Main differences:
- Access:
- Instance members are accessed through an object of the class:
ClassName object = new ClassName(); object.instanceVariable; object.instanceMethod(); - Static members are accessed through the class name or through an object:
ClassName.staticVariable; ClassName.staticMethod(); object.staticVariable; object.staticMethod();(Accessing through an object is not recommended).
- Instance members are accessed through an object of the class:
- Lifetime:
- Instance members are created when each object of the class is created and destroyed when the object is no longer accessible (garbage collection).
- Static members are created when the class is loaded into JVM memory and exist until the class is unloaded.
- Memory:
- Each object of the class has its own copy of instance members, stored in the object's memory.
- There is only one copy of each static member, shared among all objects of the class.
- Keyword:
- Instance members do not use the
statickeyword. - Static members use the
statickeyword.
- Instance members do not use the
- Access from other members:
- Static methods cannot directly access instance members without creating an object.
- Instance methods can access both instance and static members.
Example:
class Example {
int instanceVariable; // Instance member
static int staticVariable = 0; // Static member
// Instance method
void instanceMethod() {
System.out.println("Instance variable: " + this.instanceVariable);
System.out.println("Static variable from instance method: " + staticVariable);
}
// Static method
static void staticMethod() {
System.out.println("Static variable from static method: " + staticVariable);
// System.out.println("Instance variable from static method: " + instanceVariable); // Compilation error
}
}