What Are Inner Classes?


[Page 832 (continued)]

Inner classes were introduced in Java 1.1. This features lets you define a class as part of another class, just as fields and methods are defined within classes. Inner classes can be used to support the work of the class in which they are contained.

Java defines four types of inner classes. A nested top-level class or interface is a static member of an enclosing top-level class or interface. Such classes are considered top-level classes by Java.

A member class is a nonstatic inner class. It is not a top-level class. As a full-fledged member of its containing class, a member class can refer to the fields and methods of the containing class, even the private fields and methods. Just as you would expect for the other instance fields and methods of a class, all instances of a member class are associated with an instance of the enclosing class.

A local class is an inner class defined within a block of Java code, such as within a method or within the body of a loop. Local classes have local scopethey can only be used within the block in which they are defined. Local classes can refer to the methods and variables of their enclosing classes. They are used mostly to implement adapters, which are used to handle events.

When Java compiles a file containing a named inner class, it creates separate class files for them with names that include the nesting class as a qualifier. For example, if you define an inner class named Metric inside a top-level class named Converter, the compiler will create a class file named Converter$Metric.class for the inner class. If you wanted to access the inner class from some other class (besides Converter), you would use a qualified name: Converter.Metric.

An anonymous class is a local class whose definition and use are combined into a single expression. Rather than defining the class in one statement and using it in another, both operations are combined into a single expression. Anonymous classes are intended for one-time use. Therefore, they do not contain constructors. Their bytecode files are given names like ConverterFrame$1.class.




Java, Java, Java(c) Object-Orienting Problem Solving
Java, Java, Java, Object-Oriented Problem Solving (3rd Edition)
ISBN: 0131474340
EAN: 2147483647
Year: 2005
Pages: 275

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net