J2EEOnline J2EE






Java2 Certification  «Prev  Next»
Lesson 6Types of Nested Classes
ObjectiveOutline the 4 types of nested classes in Java..

Types of Nested Classes

Classes defined within the body of another class (or interface) are known as nested classes.
Normally you define a class, which is a top-level class directly belonging to a package.
In contrast, nested classes are classes contained within another class or interface.
Question: What is the benefit of creating classes inside another class or interface?
Answer: There are several benefits.
  1. First, you can put related classes together as a single logical group.
  2. Second, nested classes can access all class members of the enclosing class, which might be useful in certain cases.
  3. Third, nested classes are sometimes useful for specific purposes. For example, anonymous inner classes are useful for writing simpler event-handling code with AWT/Swing (which is not relevant to the OCPJP 7 exam).
For now, you can believe that nested classes are useful in some situations, so it is worth learning about them.
There are four types of nested classes in Java:
  1. Regular Inner Class
  2. Method-local Inner Class
  3. Anonymous Inner Class
  4. Static Nested class
The distinctions among these four types are not evident at first.

Static Non-static Anonymous
Non - local Static Nested Class Inner Class (Not Possible)
Local (Not possible) Local inner class Anonymous Inner Class

  1. A non-local class is defined inside a class.(Regular Inner Class)
  2. A Method-local Inner Class is defined within a code block (either a 1) method, 2) constructor, or 3) initialization block)
  3. An anonymous Inner Class, does not provide the name of the class; you just define its body.
  4. A static class is qualified using the static keyword, whereas a non-static class does not use the static keyword with the class definition.
One structure that you can create using static nested classes is to have a static subclass extend a static parent class.
The following link Static Inheritance gives an example of how this is accomplished.


To get you started, here is a question dealing with inner classes and interfaces.
Which of the following options can be a part of a correct inner class declaration
or a combined declaration and instance initialization ?
(Assume that SimpleInterface and ComplexInterface are interfaces.)
Select 2 options:
  1. private class C { }
  2. new SimpleInterface() { //valid code}
  3. new ComplexInterface(x) { //valid code}
  4. private final abstract class C { }
  5. new ComplexClass() implements SimpleInterface { }


Answer: a, b
Explanation:
c. You cannot pass parameters when you implement an interface by an anonymous class.
d. A final class can never be abstract.
e. The implements keyword is used only in a class definition and not during instantiation.