Sobes.tech
Junior — Middle

How to distinguish between instance methods, class methods, and static methods in object-oriented programming?

sobes.tech AI

Answer from AI

In object-oriented programming, methods are divided into three types:

  • Instance methods — work with a specific object of the class. They have access to the properties and other methods of that object through self (in Swift) or this (in other languages). They are called on an instance of the class.

  • Class methods — are associated with the class itself, not with a specific object. In Swift, they are declared with the keyword class func. These methods can access class properties (static), but not properties of a specific instance.

  • Static methods — are similar to class methods but cannot be overridden in subclasses. In Swift, they are declared with static func. They also operate at the class level, without access to an instance.

Example in Swift:

class Example {
    var value: Int = 0

    func instanceMethod() {
        print("This is an instance method, value = \(value)")
    }

    class func classMethod() {
        print("This is a class method")
    }

    static func staticMethod() {
        print("This is a static method")
    }
}

let obj = Example()
obj.instanceMethod()      // call instance method
Example.classMethod()     // call class method
Example.staticMethod()    // call static method

Thus, the main difference is the level at which the method operates: instance, class, or static (non-overridable) method.

How to distinguish between instance methods, class… - sobes.tech