Java Reference
In-Depth Information
Any static variable or static method can be referenced using the name of the
class: C.staticVar and C.staticMethod(5) .
The non-static components cannot be referenced without having a variable
that contains the name of an instance. Suppose a variable cVar contains the name
a1 . Then a1 's two components can be referenced using cVar.nonStaticVar
and, say, cVar.nonStaticMethod(5) .
The inside-out rule
We consider the question of what, exactly, can be referenced from the body
of method nonStaticMethod in instance a1 . Almost all programming languages
have a general inside-out rule that can be used to answer this question.
Inside-out rule: Code in a construct can reference any of the
names that are declared or defined in that construct, together with
any names that appear in the enclosing construct(s) —unless the
name is declared twice, in which case the closer one prevails.
Naturally, there may be restrictions on this general inside-out rule. For
example, a local variable cannot be used in a statement that precedes its declara-
tion, and the use of some of Java's access modifiers ( public , protected , pri-
vate , and the default) may give further restrictions. But this general inside-out
rule is a good first step in understanding scope issues.
Here, we use the inside-out rule to determine what can be referenced from
a1.nonStaticMethod 's method body, based on Fig. 2.5:
1. The parameter and any local variables of a1.nonStaticMethod .
2. Field nonStaticVar and method nonStaticMethod itself because they
appear in an enclosing construct.
3. Static members staticVar and staticMethod because they appear in an
enclosing construct.
By the inside-out rule, method staticMethod can reference only its param-
eters and local variables, static variable staticVar , and staticMethod itself.
The inside-out rule does not let it reference components of instances a1 and a2 .
We will apply the inside-out rule in other situations later on.
2.5
Stepwise refinement
You now have an understanding of the following kinds of statements: assignment
statements, conditional statements (if- and if-else-statements), method calls,
statements to read and write on the Java console, statements to read and display
values in fields of a JLiveWindow GUI, and statements to draw in a graphics
window. With this knowledge, we discuss the task of developing sequences of
Java statements to solve some task. In an ideal setting, we use what is called top-
down programming , or stepwise refinement .
See lesson 2-5
for a discussion
of stepwise
refinement.
Search WWH ::




Custom Search