wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Why does this work ? (Question from ExamLab) Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Why does this work ? (Question from ExamLab)" Watch "Why does this work ? (Question from ExamLab)" New topic
Author

Why does this work ? (Question from ExamLab)

John Stark
Ranch Hand

Joined: Jul 19, 2011
Posts: 185
This works:


The return type of getInner() is something which does not exists for class Main as Inner is private in class A. However the code compiles fine and gives an output like A$Inner@hgdyeu. But when I replace

by

then I get the compilation error:

Main.java:12: error: toString() in Object is defined in an inaccessible class or interface
System.out.println(new A().getInner().toString());


toString() is obviously successfully called in System.out.println(new A().getInner()); as I get the corresponding output. Why does this work and System.out.println(new A().getInner().toString()); does not work?

Thanks,

John
Stephan van Hulst
Bartender

Joined: Sep 20, 2010
Posts: 3601
    
  14

You can't call methods directly on inaccessible types. However, if you cast them to one that's accessible, then you can. This is exactly what happens when you pass the Inner object to the println() method. Its signature uses the Object class, so the Inner object gets cast to Object before its toString() method is called.

Try to do the same by assigning getInner() to a variable of type Object first, before calling toString().
John Stark
Ranch Hand

Joined: Jul 19, 2011
Posts: 185
Yes, indeed this works:

Thanks a lot for the clarification.

John
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Why does this work ? (Question from ExamLab)
 
Similar Threads
Accessing Outer Class
mock question
how to access Inner class member
Strange behavior of compilers
Something weird about static imports