I've started preparing myself for the OCJP7 exam and I found this chapter that seems to be very complicated.
Let's say I have this code:
class Outer1{
interface InnerInterface{
String x = "test";
}
class InnerClass{
String x = "test";
}
}
class Outer2{
static interface NestedInterface{
String x = "test";
}
static class NestedClass{
String x = "test";
}
}
class Main{
public static void main(String [] args){
String s1 = Outer1.InnerInterface.x;
String s2 = new Outer1().new InnerClass().x;
String s3 = Outer2.NestedInterface.x;
String s4 = new Outer2.NestedClass().x;
}
}
Could you tell me why we can access Outer1.InnerInterface.x
and Outer2.NestedInterface.x
in the same manner? Inner interfaces are static by default? I'm trying to make some connections to make them more clearly.
From Oracle's Java Tutorial :
A nested class is a member of its enclosing class. Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private. Static nested classes do not have access to other members of the enclosing class. As a member of the OuterClass, a nested class can be declared private, public, protected, or package private. (Recall that outer classes can only be declared public or package private.)
Interfaces cannot be instantiated. Thus they only make sense as static. Declaring a nested interface as static is redundant.
Also, the exercise uses confusing names for the interfaces.
Both InnerClass
and NestedClass
are nested classes. But only InnerClass
is an inner class since "inner class" means "non-static nested class".
Similarly one might expect InnerInterface
to be an "inner interface" meaning "non-static nested interface"; but such a thing does not exist. Both InnerInterface
and NestedInterface
are nested interfaces and none of them are inner interfaces.
Yes, nested interfaces are implicitly static
. Section 8.5.1 of the JLS states:
A member interface is implicitly
static
(§9.1.1). It is permitted for the declaration of a member interface to redundantly specify thestatic
modifier.
Because of this, you can access x
through the nested interface in the same manner through outer classes Outer1
and Outer2
-- both nested interfaces, InnerInterface
and NestedInterface
are static
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With