When you create an object in Java, the following operations are performed automatically:
Memory is allocated for the object.
The attributes of that object are initialized to the default values by the system.
The constructor of the class is called.
Note: if no constructor method is defined for a class, one is automatically created by default .
The default constructor is a constructor without parameters that does nothing. The attributes of the object are started with the default values by the system.
Example:
public Class Persona {
private String nombre;
private String apellido;
// Cero constructor
}
public Class MainPersona {
public static void main(String[] args) {
Persona persona = new Persona();
// Se llama al constructor por defecto
}
}
A default constructor (empty) looks like this:
// Constructor vacío
public Persona() {
}
When you instantiate a class, the parent class must have at least one constructor, even if empty, but you must have one. If you do not have it, you will receive the error:
The constructor Person () is undefined
Then, to solve this error you must have the empty constructor in the following way:
public Class Persona {
private String nombre;
private String apellido;
/*
* Constructor vacío
* Evita el error "The constructor Persona() is undefined"
* cuando se instancia esta clase en alguna otra clase
*/
public Persona() {
super();
}
}
If you need another constructor in the parent class, you can have it, you can have the number of constructors you need, example:
public Class Persona {
private String nombre;
private String apellido;
/*
* Constructor vacío
* Evita el error "The constructor Persona() is undefined"
* cuando se instancia esta clase en alguna otra clase
*/
public Persona() {
super();
}
// Constructor
public Persona(String nombre, String apellido) {
super(); // Llama al constructor vacío primero
this.nombre = nombre;
this.apellido = apellido;
}
}
I hope I have helped you!