Question

Why is it possible to define inner (aka non-static nested) classes into an interface?

Does it make any sense? They cannot exists within an instance of the containing interface, because interfaces cannot be instantiated, so...

The following does compile:

interface MyInterface
{
    static class StaticNestedClass
    {
        static int a()
        {
            return 0;
        }
        int b()
        {
            return 1;
        }
    }
    class InnerClass
    {
        static int a()
        {
            return 0;
        }
        int b()
        {
            return 1;
        }
    }
}

Is there any difference between the 2 above classes? Is static actually taken into account? Note that if you change interface with class, you obviously get a compile error on InnerClass' static int a().

Furthermore, have a look at the following:

interface MyInterface
{
    int c=0;
    static class StaticNestedClass
    {
        static int a()
        {
            return c;
        }
        int b()
        {
            return c+1;
        }
    }
    class InnerClass
    {
        static int a()
        {
            return c;
        }
        int b()
        {
            return c+1;
        }
    }
}

Unlike when the outer containing entity is a class, here of course there is no such thing as "an inner (non-static nested) class can access outer's fields while a static nested class can't", because, given that our outer thingie is an interface, our c integer is implicitly static... Are interface's nested classes implicitly static too?

So once again, are StaticNestedClass and InnerClass just the same?

Was it helpful?

Solution

class InnerClass 

is implicitly(converted to by the compiler as per JLS, Section 9.5)

A member type declaration in an interface is implicitly static and public. It is permitted to redundantly specify either or both of these modifiers.

static class InnerClass

because it is in an interface.

You will get the error when changing interface to class, because non-static Inner Classes are not allowed, and it's not implicitly converted to static in the case of a class.

To answer your final question directly,

yes, StaticNestedClass and InnerClass are just the same

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top