Junior — Middle
Explain the concept of static elements in programming and their purpose.
sobes.tech AI
Answer from AI
Static elements in programming are class members (variables or methods) that belong to the class itself rather than to any specific instance. They exist as a single instance and are accessible without creating an object of the class.
Purpose of static elements:
- Storing common data that should be shared among all objects of the class.
- Implementing auxiliary functions that do not depend on the state of an object.
- Convenient access to functionality without the need to create an instance.
Example in Swift:
class Counter {
static var totalCount = 0
func increment() {
Counter.totalCount += 1
}
}
Counter.totalCount // 0
let c1 = Counter()
c1.increment()
Counter.totalCount // 1