This week's book giveaway is in the JavaScript forum.
We're giving away four copies of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js and have Paul Jensen on-line!
See this thread for details.
Win a copy of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js this week in the JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Why does this work ? (Question from ExamLab)  RSS feed

 
John Stark
Ranch Hand
Posts: 185
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Saloon Keeper
Posts: 7713
141
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 185
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, indeed this works:

Thanks a lot for the clarification.

John
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!