SCJP – Inner Classes

[[pageindex]]

Don't forget

  • Inner classes cannot have static methods. Exception is static inner classes.

Classes in the same file - NOT inners classes

  • not inner classes
  • there can only be one public class per .java file, as public classes must have the same name as the source file.

 

 

Inner classes (class inside a class)

  • inner class can't have static declarations of any kind

Instantiating an Inner Class

  • from Within the Outer Class
MyInner in = new MyInner();  //make sure that we are not in a static context.
  • from outside the Outer Class Instance Code
MyOuter.MyInner inner = mo.new MyInner();
or
outerObjRef.new MyInner();

Referencing the Outer Instance from Within the Inner Class

MyOuter.this   //just 'this' is a reference to the inner class
  • to access members of the outer class the syntax is as the following: Outer.this.name;

Method Local Inner Classes (class inside a method)

  • inner class can't have static declarations of any kind
  • An inner class defined inside a method cannot access the method local variables unless these local variables are final
    • this because if method ends, and the reference to the inner class stills live, the local variables are not preserved anymore
  • can see the any (private or not) member of the outer class.
  • A method-local inner class can be instantiated only within the method where the inner class is defined.
  • Inner class inside method cannot have static members or blocks

Anonymous inner classes

  • inner class can't have static declarations of any kind
  • Popcorn p = new Popcorn() {} ;        where Popcorn can be a interface or class
    • if new methods are defined they are not visible using Popcorn interface, of course.
  • semicolon at the end - because this is just an assignment with an extra class definition
  • anonymous inner classes can be declared on method and constructors and also in initilization blocks

Static Nested Classes

  • The class itself isn't really "static"; Static inner classes doesn't share any relationship with outer class.
  • new BigOuter.Nest();
  • A static inner class cannot be instantiated by an instance of the outer class
    • new Outer().new Inner()  //compilation error

Visibility

  • Inner classes are visible from the outer class, even if the inner have private modifiers
    • It's possible to invoke a private inner class constructor

Modifiers

  • For inner classes only abstract and final modifiers are allowed

Tags:

Leave a Reply