• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Inner class and interface

 
Siva kandasamy
Ranch Hand
Posts: 139
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi
See the code below.
I unable to compile, if I uncomment the line "// t2.testA();".
Here my understaning is, it gives error, because,
the method "testA()" is not declared in the interface Orange.
Which makes sense. If that is the case, why java allows us to
define method "testA" at the time I implement interface Oracle
in class "Test"
In other words, what is the purpose of method "testA",
when I am unable to use it.
Hope I make sense.

 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you add methods to an anonymous class this way, it's true that you can't call then from other code. But you could call them from within the anonymous class itself, and that's why Java must allow you to define new methods in an anonymous class.
By using reflection, you actually could call that method from outside of the anonymous class: you could ask the instance for its Class object with getClass(), then get a list of Method objects with getDeclaredMethods(), and then call the "orphaned" method using the appropriate Method object.
 
Siva kandasamy
Ranch Hand
Posts: 139
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ernest,
Thank you.
BTW, don't you think that this is violating the access specifier rule.
Given the fact that, the instance is fully available to the main method.
thanks
siva
 
Siva kandasamy
Ranch Hand
Posts: 139
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Ernest,
Thanks for your input. I think I got it.
Type Orange don't have method testA, but Orange2 does have method testA defined in it.
thanks
siva
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic