Java Quick Reference
  Language Fundamentals
  Operators and Assignments
  Flow Control and Exceptions
  Declarations and Access Control
  Garbage Collection
  Overloading and Overriding
  Threads
  The java.lang Package
  The java.util Package
  The java.awt Package
  The java.io Package
  References
  Miscellaneous Notes
  Tips & Traps
  Mock Exams

Overloading, Overriding, Runtime Types and Object Orientation - Inner Classes

  • Inner classes are non-static classes defined within other classes (JLS§8.1.2)
    class Outer {
        class Inner {}      // class definition within the
                            // the body of class Outer
    }
  • the compiled class files for the above are: Outer.class and Outer$Inner.class
  • the Inner class type is: Outer.Inner
  • instances of inner classes can be created in a number of ways
Create an Outer class object:
    Outer o1 = new Outer();

Then create an Inner class object:
    Outer.Inner i1 = o1.new Inner();    

Or, create the inner class directly:
    Outer.Inner i2 = new Outer().new Inner();
    
Or, create one from within the outer class constructor
    class Outer {
        Outer() {
            new Inner();
        }
    }    
  • inner classes may have no declared access modifier, defaulting the class access to package
  • or, inner classes may be declared public, protected, private, abstract, static or final
class Outer {
    public class PublicInner{}
    protected class ProtectedInner {}
    private class PrivateInner{}
    abstract class AbstractInner {}
    final class FinalInner {}
    static class StaticInner {}
}    
  • each instance of a non-static inner class is associated with an instance of their outer class
  • static inner classes are a special case. See Static Inner Classes
  • inner classes may not declare static initializers or static members unless they are compile time constants ie static final var = value; (JLS§8.1.2)
  • you cannot declare an interface as a member of an inner class; interfaces are never inner (JLS§8.1.2)
  • inner classes may inherit static members (JLS§8.1.2)
  • the inner class can access the variables and methods declared in the outer class
  • to refer to a field or method in the outer class instance from within the inner class, use Outer.this.fldname

Example Code

Encapsulation Polymorphism isA/hasA Overloading Overriding Field Variables
Initialization Top-level Classes Inner Classes Static Nested Classes Local Classes Anonymous Classes