JavaNestedClasses
MovedToGoogleWiki
Inner Classes[edit]
An inner class in contrast to a top level class is a class that is defined inside another class. Inner classes can access everything of the outer class. Inner classes are the only classes that can be private. Es gibt vier Arten von inner classes:
- statische innere Klassen (nested top-level class)
- Elementklasse (member class)
- Lokale Klassen (in Methoden)
- Anonyme innere Klassen
Inner classes are handled by the compiler. The virtual machine does not know anything about it. The name of the inner class is <OuterClassName>$<InnerClassName> and there are normal class files generated prefixed with an $.
Static inner classes[edit]
Static inner classes or nested top level classes are declared and used like this:
public class Lamp
{
static String s = "hi";
int i = 1;
static class Bulp
{
void printHi()
{
System.out.println( s );
// System.out.println( i ); // error, because i is not static
}
}
public static void main(String[] args)
{
Bulp bulp = new Lamp.Bulp();
bulp.printHi();
}
}
There is no difference between a top level class and a nested top level class. You don't need an object of the outer class to use it.
Member classes[edit]
Declaration and instantiation:
public class Frame
{
String s = "hi";
class Pattern
{
void printHi()
{
System.out.println(Frame.this.s);
}
}
}
Frame f = new Frame; Frame.Pattern p1 = f.new Pattern(); Frame.Pattern p2 = new Frame().new Pattern();
The member class can access everything, even the private member, of the outer class. There must be an object of the outer class to create an inner class object. The inner class may not have any static properties.
Local classes[edit]
Local classes are declared as an assignment. There is no access modifier for the class or methods or any static property. A local class can access every method of the outer class and any final attributes.
Anonymous classes[edit]
An anonymous class behaves just like a local class, and is distinguished from a local class merely in the syntax used to define and instantiate it. Anonymous classes can not have an ctor because the ctor must have the same name as the class and this class doesn’t have a name. There is another feature, accessing parameters, which is very special and not recommended.
Die Declaration erfolgt durch:
new <Classname>(<optional argument list>)
{
<ClassBody>
}
An popular example of such an anonymous class is an implementation of an predefined adapter for event handling:
AddMouseListener(new MouseAdapter()
{
public mousePressed()
{
...
}
}
);