Instance Variables, Parameter Variables,and Local VariablesComputer Programming I Instructor: Greg ShawCOP 2210 Instance Variables, Parameter Variables,and Local VariablesIn recent sample programs (ChangeMaker.java, Balloon.java,BankAccount.java) we see examples of three different kinds ofvariables.Here, we are not talking about the type of data stored in thevariable, but about how the variable is used in the program.These three kinds of variables - instance variables, parametervariables, and local variables - differ in their scope,lifetimes, and initial values.- The scope of a variable refers to that portion of a programin which the variable can be accessed (i.e., where it is“known”).- The lifetime of a variable refers to the time that itactually exists. In others words, when is it created(“born”) and when is it destroyed (“dies”)?- The initial value refers to the value stored in the variable- if any - when it is first createdInstance Variables Parameter Variables Local VariablesWhereDeclaredWithin the class declaration (but not within a method declaration)In the parentheses following the method name in the method headingIn a method (but not inthe parameter list)ScopeClass-wide. Each objectcreated has its own setof instance variables, which can be accessed by all methods of the classCan be accessed only within the method in which they are declaredSame as parameter variablesLifetimeBorn when an object is created via the new operator.Die when the object dies (i.e., when the program ends or when the object is “garbage collected”)Born when the method iscalled, die when the method finishes executing.If the method is calledagain, they are born again and re-initialized. They do not retain their previous values.Same as parameter variablesInitializationUsually initialized explicitly in the classconstructor.If they are not explicitly initialized,Java will automaticallyprovide an initial value (see the handout on Java Data Types)Automatically get the values of the corresponding argumentswhen the method is called.Must be explicitly initialized within the method. Otherwise, they contain “garbage.”(Note that this is the only difference betweenlocal variables and method parameters)Fortunately, the compiler will not allowyou to use a local variable before it has been
View Full Document