• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Class Variable access

 
sanjay pathak
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class A
{ public static final int i = 10;
public ststic void main(String arg[])
{
int i = 23; // it compiles but if int i is replaced by i then
//error why
System.out.println("Value of i ="+i);
}
}
This confuses me since i is class variable then is it possible to define the variable with the same name as local in method
 
Bosun Bello
Ranch Hand
Posts: 1511
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's because "i" is declared to be final. A final variable can not be changed once it has been assigned a value. Take the final modifier off, and it will compile.
Bosun
 
sanjay pathak
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It is compiling with int i. Should it not give error saying that duplication of declaration.
 
Randall Twede
Ranch Hand
Posts: 4469
3
Java Python Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It is because the class variable is being shadowed by the local variable. From the JLS:
6.3.1 Shadowing Declarations


Since the scope of a class variable includes the entire body of the class (�8.2) the class variable x would normally be available throughout the entire body of the method main. In this example, however, the class variable x is shadowed within the body of the method main by the declaration of the local variable x.

------------------
Dont blindly believe everything I say.
[This message has been edited by Randall Twede (edited March 19, 2001).]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic