7.8 SCOPE OF AN IDENTIFIER IN JAVA


7.8 SCOPE OF AN IDENTIFIER IN JAVA

Java does not permit global identifiers with file scope; all identifiers must be local to classes in which they are declared. With regard to local identifiers, as in C++, they may be declared anywhere in a program. All local identifiers have block scope; that is, they are recognized from the point of their declaration to the end of the block containing the declaration. Java does not permit redeclaring an identifier in an inner block if it has already been declared in the enclosing block. For illustration, the following Java program does not compile because of the repeated declarations of the variable of the same name inside the nested block inside main.

 
class Test { // will NOT compile public static void main( String[] args ) { int x; x = 1; { int x; x = 2; } x = 3; } }

However, there is no problem with the name of a variable inside a method being the same as the name of a data member. For example, in the following legal program we have a data member of name x and a local variable in main of name x:

 
//ScopeText.java class Test { public int x = 100; public static void main(String[] args) { int x; // local x hides data member x x = 3; // assigns to the local x Test testObj = new Test(); testObj.x = 200; System.out.println( "Local x: " + x ); // 3 System.out.println( "Data member x: " + testObj.x // 200 } }

Of course, if you want to access the data member x inside main, you have to do so through an object of type Test, as we have done via the object testObj.




Programming With Objects[c] A Comparative Presentation of Object-Oriented Programming With C++ and Java
Programming with Objects: A Comparative Presentation of Object Oriented Programming with C++ and Java
ISBN: 0471268526
EAN: 2147483647
Year: 2005
Pages: 273
Authors: Avinash Kak

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net