Difference between static and instance variables
1. Static Variables:
Difference between static and instance variables
- Static Variables:
• Belong to the class: Shared among all instances of the class.
• Single copy: Only one copy exists in memory, regardless of how many objects are created.
• Accessed via the class: Can be accessed using the class name (ClassName.variable).
• Use case: For constants or values shared across all objects.
- Instance Variables:
• Belong to the object: Each object has its own copy.
• Multiple copies: Every object created has its own separate memory space for instance variables.
• Accessed via objects: Requires an object to access.
Example:
class Car {
static String manufacturer = "Tesla"; // static variable
String model; // instance variable
Car(String model) {
this.model = model;
}
}
public class Main {
public static void main(String[] args) {
Car car1 = new Car("Model S");
Car car2 = new Car("Model 3");
// Static variable (shared among all objects)
System.out.println(Car.manufacturer); // Tesla
// Instance variables (unique to each object)
System.out.println(car1.model); // Model S
System.out.println(car2.model); // Model 3
}
}
• Static variables are class-level and shared by all objects.
• Instance variables are object-level, with each object having its own copy.
메타데이터
- post_id
- bfa2988d0806
- slug
- difference-between-static-and-instance-variables-bfa2988d0806
- url
- https://medium.com/@NextGenML/difference-between-static-and-instance-variables-bfa2988d0806
- canonical_url
- https://medium.com/@NextGenML/difference-between-static-and-instance-variables-bfa2988d0806
- author_url
- https://medium.com/@NextGenML
- status
- ok
- fetched_at
- 2026-07-22 11:47:57