Where should you use inner classes? Code without inner classes is more maintainable and readable. When you access private data members of the outer class, the JDK compiler creates package-access member functions in the outer class for the inner class to access the private members. This leaves a security hole. In general we should avoid using inner classes. Use inner class only when an inner class is only relevant in the context of the outer class and/or inner class can be made private so that only outer class can access it. Inner classes are used primarily to implement helper classes like Iterators, Comparators etc which are used in the context of an outer class.
Member inner class | Anonymous inner class |
public class MyStack { private Object[] items = null; … public Iterator iterator() { return new StackIterator(); } //inner class class StackIterator implements Iterator{ … public boolean hasNext(){…} } }
| public class MyStack { private Object[] items = null; … public Iterator iterator() { return new Iterator { … public boolean hasNext() {…} } } }
|
Explain outer and inner classes?
Class | Type | Description | Example |
Outer Class | Package member class or interface
| Top level class. Only type JVM can recognize.
| class Outside{} Outside.class
|
Inner Class | static nested class or interface
| Defined within the context of the top-level class. Must be static & can access static members of its containing class. No relationship between the instances of outside and Inside classes.
| //package scope class Outside { static class Inside{ } } Outside.class ,Outside$Inside.class
|
Inner Class | Member class
| Defined within the context of outer class, but non-static. Until an object of Outside class has been created you can’t create Inside.
| class Outside{ class Inside(){} } Outside.class , Outside$Inside.class
|
Inner Class | Local class
| Defined within a block of code. Can use final local variables and final method parameters. Only visible within the block of code that defines it.
| class Outside { void first() { final int i = 5; class Inside{} } } Outside.class , Outside$1$Inside.class
|
Inner Class | Anonymous class
| Just like local class, but no name is used. Useful when only one instance is used in a method. Most commonly used in AWT event model.
| class Outside{ void first() { button.addActionListener ( new ActionListener() { public void actionPerformed(ActionEvent e) { System.out.println(“The button was pressed!”); } }); } } Outside.class , Outside$1.class
|
No comments:
Post a Comment