Tutorial 7: Anonymous Inner Classes


Introduction

This tutorial consists of several exercises on using anonymous inner classes as "helper" objects in the visitor pattern.  In most cases, the main visitor only needs to create the helper visitor on-the-fly and uses it internally.  It is most convenient to make the helper visitor as an anonymous inner object of the main visitor.  This way, the helper visitor is known only to the outer main visitor, thus enforcing information hiding.  Also since an inner object has access to all the internals (i.e. fields, methods, other inner objects, etc.) of the outer object, in many cases we need not pass any parameter to the anonymous inner visitor.  The drawback is sometime the code may be hard to read.

When an inner object is created inside of a method, it has access to all the   local variables that are final.  By local variables, we mean both the parameters of the method and the variables that are declared locally.  We can add the key word final to any  parameter of a method and not change the method's signature.  For example, a concrete visitor of an LRStruct may have its forNonEmpty method declared as Object forNonEmpty (final LRStruct host, Object inp).  An inner object created inside of this method will have access to the parameter host.

To help you familiarize with writing anonymous inner classes, I re-use some of the exercises you have already done and reformulate them using inner classes.


  1. Look at the solution ToString of question 2 in exam 1.  Rewrite ToString using anonymous inner classes as helpers.
  2. Look at the solution Add of question 4 in exam 1.  Rewrite Add using anonymous inner classes as helpers.
  3. Look at the solution LastNElements of question 5 in exam 1.  Rewrite LastNElements using an anonymous inner classes as helpers.
  4. Assume a LRStruct host contains Integer objects.  Write a visitor called RemMin to find, remove, and returns the minimum Integer object in the host.  Use anonymous inner classes as helper visitors.
  5. Assume a LRStruct host contains Integer objects.  Write a visitor called SwapMinWithFirst to find the minimum Integer object in the host, swap the content of the first node in the host with it, and return it.   Use anonymous inner classes as helper visitors.

 

D. X. Nguyen, Oct. 19, 2000
dxnguyen@cs.rice.edu