• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Liutauras Vilda
  • Campbell Ritchie
  • Tim Cooke
  • Bear Bibeault
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Knute Snortum
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Ganesh Patekar
  • Stephan van Hulst
  • Pete Letkeman
  • Carey Brown
Bartenders:
  • Tim Holloway
  • Ron McLeod
  • Vijitha Kumara

do not understand code that creation and definition of a class are combined together.  RSS feed

 
Ranch Hand
Posts: 253
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The following code is presented in a book.
I do not understand the code between the line A and B, specifically creation (by "new") and definition of a class are combined together.
I usually see code that the class is defined first, then it is created (by "new") later.
Is there a name for this style of coding?
 
author
Sheriff
Posts: 23589
138
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
See...

http://download.oracle.com/javase/tutorial/java/javaOO/nested.html

Or you can google for "anonymous inner class".

Henry
 
Sheriff
Posts: 11343
Java Mac Safari
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Typically, when a class is created, the keyword "new" is followed by a constructor call, and that's the end of the line.

An anonymous inner class adds a class body immediately after the constructor. Note that the end-of-line semicolon is still required!

The resulting instance is a type that has no name (and is therefore anonymous) but is a subclass of the named constructor. The reference is upcast to the constructor type. And due to polymorphism, the instance will behave according to the anonymous class definition.

(Note: Because the anonymous class is a subtype that is overriding methods, an abstract class or interface can be used as the supertype.)
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!