Java Reference
In-Depth Information
Let's change the declaration of the class
E
in the above examples to the following:
// The following code won't compile
public class E {
public class F extends A.B {
}
}
This code will not compile. In order to create an instance of the inner class
F
, you need an instance of
A.B
, which
in turn requires an instance of class
A
. In the earlier case,
E
was inherited from
A
. Therefore, it was guaranteed that an
instance of
A
exists when an instance of
E
is created. An instance of
F
can only be created when you have an instance
of its ancestor's
A.B
's enclosing class
A
. When
E
inherited from
A
, it was guaranteed, when an instance of
F
is created,
you always have an instance of class
A
. In order to make the above code work, you need to apply the same logic as you
did for class
G
. You need to declare a constructor for class
F
that takes an instance of class
A
as its parameter, like so:
// The following code will compile
public class E {
public class F extends A.B {
public F(A a) {
a.super(); // Must be the first statement
}
}
}
No static Members in an Inner Class
The keyword
static
in Java makes a construct a top-level construct. Therefore, you cannot declare any static
members (fields, methods, or initializers) for an inner class. The following code will not compile because inner class
B
declares a static field
DAYS_IN_A_WEEK
:
public class A {
public class B {
// Cannot have the following declaration
public static int DAYS_IN_A_WEEK = 7; // A compile-time error
}
}
However, it is allowed to have static fields in an inner class that are compile-time constants.
public class A {
public class B {
// Can have a compile-time static constant field
public final static int DAYS_IN_A_WEEK = 7; // OK
// Cannot have the following declaration, because it is not a compile-time
// constant, even though it is final
public final String str = new String("Hello");
}
}