Skip to content

Constructors

Constructors are special methods that initialize objects when they are created with nuevo.

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
}
}
// Instantiation
Usuario persona = nuevo Usuario("Ana", 28)

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
}
}

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
}
}

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)
}
}
  • Keep constructors focused on initialization
  • Validate parameters and throw exceptions for invalid values
  • Initialize all required attributes
  • Call parent constructors first when using inheritance