• Post Reply Bookmark Topic Watch Topic
  • New Topic

Override method on Object initilaisation  RSS feed

 
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

I stumbled on a new way to override a method that i have never seen before, while reading http://java.sun.com/products/jfc/tsc/articles/jtree/



Why is this method not mentioned in the books i have read (Head First Java, SCJP Study Guide)?

Is this style considered bad programming? I couldn't find anything on google about it.
 
Ranch Hand
Posts: 826
Chrome Eclipse IDE Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is an anonymous inner class where the print() method is overridden.Read about inner classes from here.
Hope this helps.
 
Marshal
Posts: 56600
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The reason it isn't in Head First is the same reason as why I'm moving you to the intermediate forum . . .
 
Campbell Ritchie
Marshal
Posts: 56600
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
. . . Now we are in "intermediate":

I see you have been told that is an anonymous class, which is by no means a beginner's topic, so it doesn't appear in the Head First book. Remember the Head First books are specifically aimed at beginners and omit the more complicated parts of their subjects.

There is a nice chapter about inner classes in Thinking in Java by Bruce Eckel. If you google for it, you can find a legal HTML copy of the old editions on the web.

The anonymous inner class you show is a subclass of A, with its print method overridden. What you have actually created is an object of a subclass of A.
You can override any instance methods like that in an anonymous class, but you cannot implement new constructors. So your anonymous A has the same constructor as the original A, viz the default constructor.

If you are threading, or using Listeners in Swing, you will find you are implementing the methods in the Runnable or XXXListener interfaces all the time, and using those implementations as anonymous classes.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!