Back to questions
JuniorTheoryCommon
What does the program print?
public class Main {
static void g(Object o) { System.out.print("Object"); }
static void g(String s) { System.out.print("String"); }
public static void main(String[] args) {
Object x = "hi";
g(x);
g("hi");
}
}ObjectString
- Expecting
StringString: the object inxis a string, but the compiler picks an overload before the program runs, by the declared typeObject. - Expecting
ObjectObject: the literal"hi"is aString, sog(String)matches it exactly and wins overg(Object).
- How would you make
g(x)callg(String)without changing the declaration ofx? - Which version of an overridden method runs when it is called through a variable of type
Object?