Sobes.tech
Junior — Middle

Kas on kohustuslik, et klassil oleks konstruktor, et see korralikult töötaks?

sobes.tech AI

Vastus AI-lt

The presence of a constructor in a class is not always necessary for its correct operation. If no constructor is declared in the class, the compiler automatically creates a default parameterless constructor.

However, if initialization with parameters or special logic during object creation is needed, the constructor must be explicitly declared.

Example in Swift:

class Person {
    var name: String
    
    // Constructor is mandatory because there is a required property without a default value
    init(name: String) {
        self.name = name
    }
}

If all properties have default values, writing a constructor is not necessary, and the class will work correctly.