Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Inner and anonymous class method inheritance

 
J. Nuno
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

If I run this the output is My Frog speaking...



If I run this the output is Frog speaking...



And if I run this the output is again My Frog speaking...



I'm lost, can someone explain me this behaviour? Thanks!
 
Maurizio Nagni
Ranch Hand
Posts: 75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You are right it is a curious situation, but with some logic we can get out of this "paradox".
The private signature forbidden any call outside the class it is defined, that's clear, and that's why anyway you cannot call from your ovrerridden method: because is private, it calls the "speak" method of the class the call is in.
May be to make it more clear try to compare your code with



you will receive an error because speak() is private

To make it worthly work your code should look something like

now the oroginal method is protected, but it print out "My Frog is speaking..." as you expected because the method can be called outside the class it is defined.
 
rakesh sugirtharaj
Ranch Hand
Posts: 151
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The explanation could be -
Case 1 : It is normal anonymous class behaviour, so doesnt require explanation.
Case 2 : private methods cannot be overridden. And also note that the reference is actually of a parent Frog. Since the method is private, at run time the child anonymous inner is not even checked for a override.
Case 3 : Here there is no parent reference and it is similar to calling the anonymous child inner method.
Summing up - Its the reference Frog f that is making the difference.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic