Junior — Middle
Is it mandatory to have a constructor in a class for it to work correctly?
sobes.tech AI
Answer from AI
Having a constructor in a class is not always necessary for it to function correctly. If no constructor is declared in the class, the compiler automatically creates a default constructor without parameters.
However, if parameterized initialization or special logic during object creation is needed, then the constructor should be explicitly declared.
Example in Swift:
class Person {
var name: String
// Constructor is required because there is a mandatory property without a default value
init(name: String) {
self.name = name
}
}
If all properties have default values, then the constructor can be omitted, and the class will work correctly.