static and final variables in Java
variables estáticas y finales en Java
class AndroiPhone{
//Declare and initialize variables
static double versionNumber = 2.2;
boolean turnedOn = false;
final String color = "blue";
public static void main (String[] args) {
...
}
}
...
/*
Pretend that we live in a world where you can make real life changes happen with Java.
Let's say Samsung has created 10 Android Phones using the AndroidPhone class above.
The next day, 10 users purchase these phones.
We will label them
phoneOne,
phoneTwo,
phoneThree,
and so on.
When (if ever) Samsung releases an update, they would want all 10 of these devices
to get the update together (I know this isn't a very realistic scenario, just pretend)!
So they would use Eclipse to say:
*/
static void updatePhones(){
versionNumber = 2.3;
}
/*
(Note: If you take the equal sign too mathematically, it will confuse you.
So, whenever you give a value to a variable, try and interpret it like this:
"versionNumber is TAKES THE VALUE OF 2.3." It will make it easier to conceptualize).
Recall that we created a static double (decimal variables) called versionNumber.
This means that when you change the value of versionNumber once, it will affect
every instance of the AndroidPhone class, meaning that all 10 AndroidPhones will
receive the update immediately!
It makes sense to create a static variable for the versionNumber, but it does not
make sense to create a static variable for the power! You don't want the user to
be able to turn off other people's phones - you want each phone to have its own
"turnedOn" boolean (True/False variables).
How, then, do you select which phone will turn on or off?
It's rather simple!
Remember that we labeled each of these phones (phoneOne, phoneTwo, etc).
*/
//Now the final variable,
final String color = "blue";
/*
String means text, and we are creating a color variable with the value of "blue"
(quotes indicate literals. no quotes would give color the value of a variable called blue).
The color of these 10 AndroidPhones will never change (ignore spraypaint and
cases). So, we just indicate that they are "final."
*/
static and final variables in Java
variables estáticas y finales en Java