Fields
are variables within a class or struct, local variables
sit within a method and global variables
are accessible in every scope (class and method included).
This makes me think that fields
might be global variables
but that global variables
are not necessarily fields
although I cannot think of a variable sitting outside of a class.
Is there a clear difference between the two?
In Java, all the variables must be declared before use. Field A data member of a class. Unless specified otherwise, a field can be public, static, not static and final.
Variables are classified into Global variables and Local variables based on their scope. The main difference between Global and local variables is that global variables can be accessed globally in the entire program, whereas local variables can be accessed only within the function or block in which they are defined.
Key Differences between Local Variable and Global Variable Local variables are created when the function has started execution and is lost when the function terminates, on the other hand, a Global variable is created as execution starts and is lost when the program ends.
A global variable can be accessed from anywhere inside the program while a static variable only has a block scope. So, the benefit of using a static variable as a global variable is that it can be accessed from anywhere inside the program since it is declared globally.
You tagged this C# and C# does not really have 'global variables'.
But a public static
field (or property) would come close. The static makes it singular and gives it a 'global' lifetime.
I think Wikipedia's definition is appropriate here:
In object-oriented programming, field (also called data member or member variable) is the data encapsulated within a class or object. In the case of a regular field (also called instance variable), for each instance of the object there is an instance variable: for example, an Employee class has a Name field and there is one distinct name per employee. A static field (also called class variable) is one variable, which is shared by all instances.
So a global variable is pretty much a static field (and therefore, a field).
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