In what situations we can use innerclass and anonymous class

Questions by raambabu

Showing Answers 1 - 2 of 2 Answers

rabbi

  • Jun 29th, 2006
 

 To help you get a handle on inner classes and what they are good for, let's visit the "Stack" class.Here's a "Stack" implementation that defines a helper class, called StackIterator , for enumerating the stack's elements:

public class Stack {    private ArrayList<Object> items; // <object> is generics. for more info view jdk1.5    public Iterator<Object> iterator() {        return new StackIterator();    }    private class StackIterator implements Iterator {        int currentItem = items.size() - 1;        public boolean hasNext() {            ...        }        public ArrayList<Object> next() {            ...        }        public void remove() {            ...        }    }}

  The "Stack" class itself should not implement the "Iterator" interface, because of certain limitations imposed by the API of the "Iterator" interface: two separate objects could not enumerate the items in the "Stack" concurrently, because there's no way of knowing who's calling the next method; the enumeration could not be restarted, because the "Iterator" interface doesn't have methods to support that; and the enumeration could be invoked only once, because the "Iterator" interface doesn't have methods for going back to the beginning. Instead, a helper class should do the work for "Stack".    The helper class must have access to the "Stack's" elements and also must be able to access them directly because the "Stack's" public interface supports only LIFO access. This is where inner classes come in.  

 Inner classes are used primarily to implement helper classes like the one shown in this example. If you plan on handling user-interface events, you'll need to know about using inner classes because the event-handling mechanism makes extensive use of them.      

 You can declare an inner class without naming it, called an anonymous class.  An anonymous class is generally used inside an expression and it does not have member scope, since it isn't visible to the enclosing class.  

  Was this answer useful?  Yes

siva kumar reddy

  • Aug 9th, 2006
 

hi,

a class with in the class is called innerclass.it is a safety mechanisam.innerclass variables are accessed througth outerclass variables only.

anonymous class is an innerclass whose class name will be hidden .whom will be created only object.

cheers

siva

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions