| Author |
Difference between a Variable and a Field?
|
Div Raj
Greenhorn
Joined: Nov 04, 2008
Posts: 22
|
|
Hi, 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. Could any one tell me what's the difference between a Variable and a Field? Thanks ---------
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32654
|
|
|
A field is valid (in scope) throughout the whole class/object. A field is in fact a kind of variable, but it applies to the whole class/object.
|
 |
Div Raj
Greenhorn
Joined: Nov 04, 2008
Posts: 22
|
|
ThankYou Ritchie But I've one doubt; the Class variable/Instance variable is also having their scope throughout the class/object. Right? Thanks --------
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32654
|
|
A class variable is what you call a static field. That has scope throughout the whole class, and is accessible from any method of that class, static or instance (non-static). An instance field is not accessible from any static parts of the class.
|
 |
Div Raj
Greenhorn
Joined: Nov 04, 2008
Posts: 22
|
|
ok. So could you please tell me what is a Field? Thanks -----------
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32654
|
|
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 fieldThe 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. Does that help?
|
 |
Div Raj
Greenhorn
Joined: Nov 04, 2008
Posts: 22
|
|
ok. Now I got it. ThankYou Ritchie
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32654
|
|
You're welcome
|
 |
 |
|
|
subject: Difference between a Variable and a Field?
|
|
|