Is there a difference between assigning values to variables outside of any method, and assigning these values within a constructor?
Looking at Oracle's Java tutorial, they have:
public class Bicycle {
int cadence = 0;
int speed = 0;
int gear = 1;
void changeCadence(int newValue) {
cadence = newValue;
}
is this any different from saying/why didn't they just say:
Bicycle(){
int cadence = 0;
}
If you declare the variable in your constructor, it will be local to the constructor and not visible anywhere else in your class.
If you declare a variable
inside a constructor
, this variable can only be accessed inside this constructor
. But, you can create a variable on your class
, and access it on your constructor
or method
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With