Q : If we create a custom class String in the directory structure like java.lang and import it in our class. Which version of String class would be imported : Custom class or Standard Library class ??
Ans : Java has been coded such that it would pick its Standard library class only even if we define class with same name and same package structure.
So the class might compile but would give a runtime exception if we try to invoke a method which we defined in our custom class n which is not present in the std library class.
e.g.
package java.lang;
public final class String {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
}
public String toString(){
return "Custom Java Class";
}
public static void myMethod(){
System.out.println("My custom java class");
}
}
and a class
import java.lang.String;
public class StringTesting {
/**
* @param args
*/
public static void main(String[] args) {
String str = new String();
java.lang.String.myMethod();
}
}
the code will compile coz at the compile time , its referring to the custom java class , but at run time, the standard java class would be loaded and since it doesnt have myMethod(), it would generate run time exception.
This is because when our custom java.lang.String class is referenced, the class loader checks if this has already been loaded and it finds that a class with the same fully classified class name has already been loaded (which is the one provided by java) and so does not load the custom java.lang.String class
No comments:
Post a Comment