Java Packages

Question : Explain Outer and Inner classes (or Nested classes) in Java? When will you use an Inner Class?
Answer : 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

public class MyStack {
private Object[] items = null;
…
public Iterator iterator() {
return new StackIterator();
}
//inner class
class StackIterator implements Iterator{
…
public boolean hasNext(){…}
}
}

Anonymous inner class

public class MyStack {
private Object[] items = null;
…
public Iterator iterator() {
return new Iterator {
…
public boolean hasNext() {…}
}
}
}

Explain outer and inner classes?

Leave a Reply