how can the compiler distinguish the "Classname"
Because there are two components: The variable type and variable name. You declare a variable ClassName
of type ClassName
. Type always goes first. Classes are not first-class objects (meaning you can't have a reference to a class) unless you get into reflections (with the .class
property).
Therefore, in the print statement:
System.out.println(ClassName);
That can only be the variable. System.out.println
takes an object reference, and you have an object referred to by a variable named ClassName
, therefore the compiler can resolve it.
The only case I can think that is ambiguous to the compiler is if the variable refers to an object which has an instance method of the same name as a static method on the class.
public class SomeClass {
public void aMethod() {
System.out.println("A method!");
}
public static void aMethod() {
System.out.println("Static version!");
}
}
public class TestClass {
public static void main (String[] args) {
SomeClass SomeClass = new SomeClass();
SomeClass.aMethod(); // does this call the instance method or the static method?
}
}
I am sure the compiler will detect the ambiguity and handle it in some specified manner (in the Java spec). Probably one of:
- Don't allow a static and instance method to have the same name.
- Allow it, and when resolving the reference at compile-time, prefer the instance method.
- Allow it, and when resolving the reference at compile-time, prefer the static method.
If either of the last 2, I imagine a compiler warning would be logged.
Now that the compiler question is aside, the only other consumer of the code is human beings. Compilers may be able to rely on specifications to guarantee rationale behavior, but humans can't. We get confused easily. The best advice I have for that is simply, don't do it!
There is absolutely no reason to name a variable identically to a class. In fact, most Java coding style conventions I have seen use lowerCamelCase to name variables and methods and UpperCamelCase to name classes, so there is no way for them to collide unless you deviated from the standards.
If I encountered code like that in a project I was working on, I would immediately rename the variable before doing anything else.
For my ambiguous case of an instance and static method of the same name, there just might be a human lesson in there too: don't do it!
Java has a lot of rules to force you to do things that are logical and make code easy to follow, but at the end of the day, it's still code and you can write any code you want. No language spec or compiler can prevent you from writing confusing code.