curious - method local class trivia

Y

yeah

Never had much use for defining classes inside methods but this is
something interesting I noticed while playing around with it. Consider
this example:

public class test {
public static void main(String args[]) {
test t = new test() ;
System.out.println( t.doIt() ) ;
}

public static Thing doIt() {
class Thing {
public int result ;
Thing(int v) { result = v ; }
}

Thing t = new Thing(4) ;
//return t ; // compile error
return null ; // compiles fine
}
}

If doIt returns null, the program compiles and outputs "null". If it
returns 't' (the new Thing), the compiler error states:

test.java:24: incompatible types
found : Thing
required: Thing
return t ;
^
1 error


Of course this is reasonable (if perverse) since the method return
type Thing presumably has a different symbol table value than the
method internal Thing class.

What's really strange to me is that this distinction is represented by
the error message. If, for instance, the return type of doIt() is
changed to ThingX, you get something like:

test.java:22: cannot resolve symbol
symbol : class ThingX
location: class A
public ThingX doIt() {
^
1 error


So it looks like the compiler isn't entirely clear on whether or not
it distinguishes between return type Thing and method-local Thing.
 
T

Tor Iver Wilhelmsen

(e-mail address removed) writes:

This uses the outer class name...
public static Thing doIt() {

.... but this is the inner class name. The classes are not related.
Thing t = new Thing(4) ;

.... and here, the method-local class is not visible to the method
declaration.
public ThingX doIt() {
^
So it looks like the compiler isn't entirely clear on whether or not
it distinguishes between return type Thing and method-local Thing.

It is very clear. Read up on namespaces: The class declaration does
not "see" the member class.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,904
Latest member
HealthyVisionsCBDPrice

Latest Threads

Top