Is there a constructor in this piece of code? Which part in this code is the constructor?
class Bicycle {
int cadance = 0;
int speed = 0;
int gear = 0;
void changeCadance(int changeCadence) {
cadance = changeCadence;
}
void changeGear(int changeGear) {
gear = changeGear;
}
void changeSpeed(int changeSpeed) {
speed = changeSpeed;
}
void printState() {
System.out.print("Cadance = "+cadance);
}
}
What you have there is an implied default constructor. It is never spelled out, but it is understood to be there by the IDE and compiler. Non static classes are generally understood to have a constructor, and thus if no constructor is created explicitly, the default constructor is used. It takes no arguments, and does not really do anything but initialize the class with the explicitly provided property values. Sometimes, you can get away with just the default.
For a little more information, I am linking the Wikipedia article for Default Constructor as I think it does a pretty good job of explaining it across several languages.
Essentially it says that the default constructor is supplied by the compiler (and the IDE will normally allow you to call it also) if a parameterless constructor is not explicitly given in the class. So if I write a constructor that takes and parameter, but I don’t write a constructor that takes no arguments, the compiler will STILL supply one.
This is a bit of a generalization as some languages differ a bit, but I think that most doe the above.