Junior — Middle
Selgitage, mida mõistetakse mõiste 'konstruktor' all objektorienteeritud programmeerimises.
sobes.tech AI
Vastus AI-lt
In object-oriented programming, a constructor is a special method of a class that is called when a new object of that class is created. Its main task is to initialize the object, that is, to set the initial values of its fields.
Features of the constructor:
- It has the same name as the class.
- It does not return a value, not even void.
- It can accept parameters for configuring the object during creation.
- If the constructor is not explicitly defined, the compiler creates a default constructor.
Example of a constructor in C#:
class Person
{
public string Name;
public int Age;
// Constructor
public Person(string name, int age)
{
Name = name;
Age = age;
}
}
// Creating an object by calling the constructor
Person p = new Person("Иван", 30);
Thus, the constructor ensures the correct initialization of the object right at its creation.