why cant I find this simple answer anywhere??: global vs. instance variables
I am getting confused between global and instance variables.
I think I got it, but cannot confirm this anywhere on the internet, somehow no one ever talks abou this.
From what I understand, a global variable is a variable that is declared outside any method of a class. (and this is also called the instance data)
An instance variable is any variable declared inside a constructor of a class.
Therefore, any instance variable also must be a global variable (and instance data).
Is this fully correct?
[545 byte] By [
shabam] at [2007-11-11 8:19:16]

# 1 Re: why cant I find this simple answer anywhere??: global vs. instance variables
I'm not sure I understand your question. I don't know what you mean when you say global variable because Java does not support globally accessible variables. You can mimic a global variable by making it public and static, like Math.PI, but you must call it from the class that it is in.
There are two main types of variables: instance variables and class variables. An instance variable is a non-static variable, making it's value specific to an instance of that class. A class variable is a static variable, making it's value the same for every instance of that class.
If you clear up what you mean by global variable I'd be glad to help. Thanks.
destin at 2007-11-11 22:35:43 >

# 2 Re: why cant I find this simple answer anywhere??: global vs. instance variables
by global variable i mean any variable that is declared in a class outside any method (or constructor). In other words variables that can be passed between methods without the use of parameters.
eg:
class Hello
{
int i=1;//global variable/instance data
public void sayHello()
{
int j=0;//this is a local as opposed to global variable relative to the
//Hello class
System.out.println("hello"+i);//this line is using the "global variable" that is
//in the
//Hello class. Here I dont have a constructor, so therefore there are no instance
// variables
}
}
shabam at 2007-11-11 22:36:48 >

# 3 Re: why cant I find this simple answer anywhere??: global vs. instance variables
class Hello
{
int i=1;//global variable/instance data
public void sayHello()
{
int j=0;//this is a local as opposed to global variable relative to the
//Hello class
System.out.println("hello"+i);//this line is using the "global variable" that is
//in the
//Hello class. Here I dont have a constructor, so therefore there are no instance
// variables
}
}
No, i is an instance variable. Instance variable simply means that the value of i is specific to each instance of Hello, which is true. Also, your class does have a constructor; if you do not specify a constructor, a default one will automatically be generated for you. If it wasn't, it would be impossible to create an instance of Hello.
Again, in Java, there is no such thing as a global variable.
destin at 2007-11-11 22:37:52 >
