Reputation: 71
Given a class shadowing a builtin class like String:
class String {
public static void main(String[] args) {
}
}
String is not a keyword, but still, the above program gives a runtime error. Why is that?
Upvotes: 0
Views: 1340
Reputation: 57982
The reason is because the main
method is 'special' in that it is the entry point of the program. The arguments of the program are specified to have a variable number of Java's java.lang.String
s, not your String class. Your string class is the closest one to the class as it's the current class, so Java uses your String class in the main
arguments when JVM expects the Java's String, thus leading to the error. You can prevent this by using the fully qualified name of Java's String:
public static void main(java.lang.String[] args) {
...
}
Upvotes: 2
Reputation: 48307
Bad thing happens, when you define a class with the name String you are shadowing a java.lang.String
Class
that means every declared object must use the full-qualified name java.lang.String
if it refers to a "normal String" other than that will point to your defined one..
example is the code you write:
public static void main(String[] args) {
}
if that is the only class you have, then the compiler will complain since the entry point for an application will never be found...
you will be need to define explicit the argument by doing
public static void main(java.lang.String[] args) {
}
this is a very nice pitfall that will break your neck, all the most because the classes in the java lang doesnt need to be imported,your code must be carefully writen and is pretty much error prone..
That code will compile but in any decent code analyzer you will get a lot of complains and rename suggestions..
I will follow that way too, and suggest never name your classes like standart java classes...
Upvotes: 2