Java Reference
In-Depth Information
The callback mechanism described in this section is used extensively in Java when working with GUI applications
developed using Swing and JavaFX.
Java 8 introduced lambda expressions that make working with callbacks more concise. I will discuss lambda
expressions in Chapter 5.
Note
Defining Inner Classes in Static Contexts
You can also define an inner class in a static context such as inside a static method or a static initializer. There is no
current instance of the outer class present in a static context, and therefore such an inner class cannot access instance
fields of the outer class. However, all static field members are accessible to such an inner class.
public class Outer {
static int k = 1001;
int m = 9008;
public static void staticMethod() {
// Class Inner is defined in a static context
class Inner {
int j = k; // OK. Referencing static field k
int n = m; // An error. Referencing non-static field m
}
}
}
Summary
Classes declared inside the body of another class are called inner classes. The class within which the inner class is
declared is known as the enclosing class. Inner classes have direct access to all members of their enclosing class.
Instances of inner classes exist only within an instance of the enclosing class, except when they are declared in a static
context, for example, inside a static method.
There are three types of inner classes: member inner class, local inner class, and anonymous inner class.
Inner classes are declared in non-static contexts. A member inner class is declared inside a class the same way a
member field or a member method for the class is declared. It can be declared as public , private , protected , or
package-level. A local inner class is declared inside a block. Its scope is limited to the block in which it is declared.
An anonymous inner class is the same as a local inner class with one difference: it does not have a name. An anonymous
class is a one-shot class; it is declared and an object of the class is created at the same time.
A class declared inside another class in a static member class is simply called a static nested class. A static nested
class has access to the static members of the enclosing class.
Inside an inner class, the keyword this refers to the current instance of the inner class. To refer to the current
instance of the enclosing class, you need to qualify the keyword this with the class name of the enclosing class.
You cannot declare a static member for inner classes. This implies that interfaces and enums cannot be declared
as members for inner classes.
 
 
Search WWH ::




Custom Search