public class Knowing {
static final long tooth = 343L;
static long doIT(long tooth) {
System.out.print(++tooth + " ");
return ++tooth;
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.print(tooth + " ");
final long tooth = 340L;
new Knowing().doIT(tooth);
System.out.println(tooth);
}
}
Okay so here is my question:
-
If we have a global variable declared
static final long tooth = 343L;How can we have another variable in the main method declaredfinal long tooth = 340L;I just want to know why this is allowed because I ran it and there was no error? -
And also shouldn’t the access of the global static variable tooth be by using className.variableName and not by creating a new instance.variable name how come that is allowed with only a warning?
Because the language specification says you can. From section 6.4.1 of the JLS, about shadowing:
Should you do this? Rarely. On the other hand, I’ve rarely seen it be a problem, either.
For your second question:
This is a design flaw in Java, IMO. Even the warning isn’t part of the language specification. You should always avoid doing this, as it makes the code do something other than it looks like it’s doing. The example I usually give is:
That makes the executing thread sleep, not the new thread.