According to my perspective and in order to contribute to your doubt
A constructor, as its name says, is a block of code that is responsible for creating an instance or initializing an object of a given class. Each class has or should have certain attributes that differentiate it from other classes (hence other objects). Constructors have no type (void, static, etc) nor return a value, its function is to always initialize all the properties or attributes of the class in question. Not necessarily always have to carry specific values, for example, a value of a property if we want (although I do not see the case well) we can start it as null in case of objects, in 0 in types numbers or in "" in types of text . There are two types of builders, with and without parameters.
Example:
We have a class called Auto with two attributes (or properties): Badge and Brand
Observation: If you do not give an access modifier (private, public, protected) by default only the own class and the package can access that property.
Not specified
- You can access: The class and the Package
Private
- You can access: only the class
Protected
- You can access: The class, the package and a subclass (in case of inheritance)
Public
- You can access: All (Class, subclass, package, etc)
Example:
public class Auto{
String placa;
String marca;
public Auto () {
}
public Auto (String placa, String marca){
this.placa = placa;
this.marca = marca;
}
}
In this particular case, the input parameters of the constructor have the same names of the properties of the class. That's why I use the this
to make specific reference to the properties of your class, although it can also be like this:
public Auto (String placaAuto, String marcaAuto){
placa = placaAuto;
marca = marcaAuto;
}
For the creation of an object type Auto, as I explained above depending on the access modifier is how you can create it
If the property indicators are public or not, it may be
Auto nuevoAuto = new Auto();
nuevoAuto.placa = "HV-45-78";
nuevoAuto.marca = "Chevrolet";
O
Auto nuevoAuto = new Auto("HV-45-78", "Chevrolet");
Both forms are valid and will help you to instantiate an object of type Auto, I hope this information helps you and complement those that others gave you.