Cloud Stack Ninja

Let's say you have a class named Vehicle:

class Vehicle {
    var name: String
    var size: Int
    
    init(name: String, size: Int) {
        self.name = name
        self.size = size
    }
    
    convenience init(name: String) {
        self.init(name: name, size: 100)
    }
    
    func operate() {
        print("operate")
    }
}

If I have a subclass named Car and create a convenience initializer:

class Car: Vehicle {
    convenience init(size: Int) {
        self.init(name: "Vehicle", size: size)
    }
}

the super class' initializer is made available using self.

But, if I want to override the super class' method, it's made available by using super:

class Car: Vehicle {
    // redacted
    
    override func operate() {
        super.operate()
        print("operate a car")
    }
}

If the subclass wants to use the inherited method, it's made available by using self:

class Car: Vehicle {
    // redacted

    func drive() {
        self.operate()
        print("drive")
    }
}

I understand that class methods are instance methods, meaning self refers to the instance of the class. I'm guessing when the subclass inherits the super class' method, it becomes its own instance method. Why does it not apply to overriding? I'm getting confused between the usage of self and super.



Read more here: https://stackoverflow.com/questions/64419645/confusion-between-self-and-super-in-a-subclass

Content Attribution

This content was originally published by Kevvv at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: