<< This Applet Not Brought To You By... | Home | Jython 2.5 Beta0 Released >>

Friday Java Quiz: Now For A Real Test

Less than an hour after I posted last weeks Friday Java Non-quiz, Steve walked in, wrote some code on the white board, and said: "This should be on your Java quiz."

Here's a simplified version of his class:

1    public class Foo { 
2        public static void main(String[] args) { 
3            Foo foo = new Foo(); 
4            foo.printIt(foo.getIt()); 
5        } 
6     
7        @SuppressWarnings("unchecked") 
8        private <T> T getIt() { 
9            return (T) "hello, world."; 
10       } 
11    
12       private void printIt(String s) { 
13           System.out.println(s); 
14       } 
15   }

The question remains the same:

Q: Compile, or no compile?

Strict rules apply: No actually running the compiler. Must back answer with JSL citation.

Tags :


Re: Friday Java Quiz: Now For A Real Test

No compile. Compiler will "infer" Object for T in foo.getIt() on line 4, which isn't compatible with printIt(String). You could make it compile by extracting a variable: String it = foo.getIt(); foo.printIt(it);

Re: Friday Java Quiz: Now For A Real Test

That version of the code:

String it = foo.getIt();
foo.printIt(it);

is actually on my white board. When I ask IDEA to inline the variable, I also get:

foo.printIt(foo.<String>getIt());

Add a comment Send a TrackBack