October 10, 2009

Difference between a Variable and a Field?

Any variable declared outside methods, initialisers, etc. If you declare a variable inside the class and not inside a method, initialiser, etc, then it is called a field
view plaincopy to clipboardprint?
1. public class Kettle
2. {
3. private int temperature;
4.
5. public void becomeHotter(int degrees)
6. {
7. int heat = temperature + degrees;
8. temperature = heat;
9. }
10.
11. public int getTemperature()
12. {
13. return temperature;
14. }
15. . . .
16. }

The variable temperature is declared inside the class and outside the methods; you call it a field. It is accessible and in scope in the two methods shown.
The "variable" degrees is "declared" inside the () for the becomeHotter() method; it is a parameter, and is not a field. Its scope is that method.
The variable heat is declared inside the becomeHotter method. It is a local variable and its scope is from "int heat . . ." to the end of the method. It is not a field.(OR)
I read in a book that, Instance variables are Non-static fields.
And Class variables are Static fields.
Also Parameters are classified as variables and not fields.

No comments:

Post a Comment

I'm certainly not an expert, but I'll try my hardest to explain what I do know and research what I don't know.

My Favorite Site's List

#update below script more than 500 posts