Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Constructors- Assigning value to variable

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;
 } 
like image 276
user2009020 Avatar asked Dec 01 '22 19:12

user2009020


2 Answers

If you declare the variable in your constructor, it will be local to the constructor and not visible anywhere else in your class.

like image 130
Todd Avatar answered Dec 04 '22 10:12

Todd


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.

like image 42
JoaaoVerona Avatar answered Dec 04 '22 09:12

JoaaoVerona