Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java inner and nested classes

Tags:

java

class

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.

like image 822
Mike Avatar asked Jul 29 '15 20:07

Mike


2 Answers

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.

like image 170
Anonymous Coward Avatar answered Oct 23 '22 14:10

Anonymous Coward


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 the static 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.

like image 26
rgettman Avatar answered Oct 23 '22 13:10

rgettman