touque.ca > Education Commons > Java > Resources

Scope & Lifetime

A formal parameter is available to an object only within the body of a constructor or method that declares it. We say that the scope of a parameter is restricted to the body of the constructor or method in which it is declared. In contrast, the scope of a field is the whole of the class definition—it can be accessed from anywhere in the same class. This is a very important difference between these two sorts of variables.

A concept related to variable scope is variable lifetime. The lifetime of a parameter is limited to a single call of a constructor or method. When a constructor or method is called, the extra space for the parameter variables is created and the external values copied into that space. Once that call has completed its task, the formal parameters disappear and the values they held are lost. In other words, when the constructor has finished executing, the whole constructor space is removed along with the parameter variables held within it. In contrast, the lifetime of a field is the same as the lifetime of the object to which it belongs. When an object is created, so are the fields, and they persist for the lifetime of the object. It follows that if we want to remember the value held in a parameter, we must store the value somewhere persistent—that is, in a field (Barnes & Kölling, 2012, pp. 29–30).

(Read in Object References how objects are treated differently than are primitive values.)


Barnes, D. & Kölling M. (2012). Objects first with Java: A practical introduction using BlueJ. Toronto: Pearson Education, Inc. ISBN 978-0-13-249266-9.

touque.ca > Education Commons > Java > Resources

[This page last updated 2020-12-23 at 12h13 Toronto local time.]