Constructors
Constructors are special methods that initialize objects when they are created with nuevo.
Basic Syntax
Section titled “Basic Syntax”The constructor has the same name as the object and no explicit return type.
objeto Usuario { privado: texto nombre entero edad
publico: Usuario(texto nombre, entero edad) { ambiente.nombre = nombre ambiente.edad = edad }}
// InstantiationUsuario persona = nuevo Usuario("Ana", 28)The ambiente Keyword
Section titled “The ambiente Keyword”Use ambiente to refer to the current object’s attributes and methods (similar to this in other languages).
objeto Rectangulo { privado: numero var ancho numero var alto
publico: Rectangulo(numero ancho, numero alto) { ambiente.ancho = ancho ambiente.alto = alto }
numero calcular_area() { retornar ambiente.ancho * ambiente.alto }}Constructor Initialization
Section titled “Constructor Initialization”You can initialize attributes directly in their declaration:
objeto Contador { entero var valor = 0
Contador() { // No additional initialization needed }
Contador(entero inicial) { ambiente.valor = inicial }}Constructors with Inheritance
Section titled “Constructors with Inheritance”When using inheritance, call the parent constructor with padre.ParentName():
objeto Animal { privado: texto nombre
publico: Animal(texto nombre) { ambiente.nombre = nombre }}
objeto Perro como Animal { publico: Perro(texto nombre) { padre.Animal(nombre) }}Best Practices
Section titled “Best Practices”- Keep constructors focused on initialization
- Validate parameters and throw exceptions for invalid values
- Initialize all required attributes
- Call parent constructors first when using inheritance