Variables and Scope
You have seen two ways that variables can be described: variables of primitive type or variables of reference type. You have also seen two places variables can be declared: inside a method (a method is an object-oriented term which refers to a function or subroutine such as main() ) or outside a method but within a class definition. Variables can also be defined as method parameters or constructor parameters.
Variables defined inside a method are called local variables, but are sometimes referred to as automatic, temporary, or stack variables.
Variables defined outside a method are created when the object is constructed using the keyword new xxxx(). There are two possible kinds of variables. The first kind is a class variable which is declared using the static keyword. This is done when the class is loaded. Class variables continue to exist for as long as the class exists. The second kind is an instance variable which is declared without the static keyword. Instance variables continue to exist for as long as the object is referenced. Instance variables are sometimes referred to as member variables, as they are members of the class. The static variable will be discussed later in this course in greater detail.
Method parameter variables define arguments passed in a method call. Each time the method is called, a new variable is created and lasts only until the method is exited.
Local variables are created when execution enters the method, and are destroyed when the method is exited. This is why local variables are sometimes referred to as “temporary or automatic” variables. Variables that are defined within a member function are local to that member function, so you can use the same variable name in several member functions to refer to different variables.
For example:
class AllCar {
// this is an instance variable of AllCar
int chassiNumber;
int findType(){
// this is a local variable
int carType;
// both chassiNumber and carType are accessible
return 1;
}
int changeType(){
// another local variable although it has the
// same name as in the findType() method
int carType;
/* the scope of carType is limited to the body of the method it’s declared in. Both chassiNumber (an instance variable of the AllCar class) and carType (a variable local to this method) are accessible here */
}
}
No comments:
Post a Comment