-1

This is my java code:

class A {
    interface That {
        void show();
    }
}

class B implements A.That {
    public void show() {
        System.out.println("Hi");
    }
}

public class MainClass {
    public static void main(String args[]) {
        A obj = new A();
        obj.That object = new B();
        object.show();
    }
}

Since A is a class (not abstract) we can create its instance and than we can use members of that instance. Now interface is member so obj.That should work but javac says that obj.That is not package. Why?

avysk
  • 1,973
  • 12
  • 18
Shubham Tyagi
  • 181
  • 1
  • 3
  • 14
  • 1
    Can you please edit your question to include the full error message? – Joe C Feb 25 '17 at 12:00
  • Possible duplicate of [Java inner class and static nested class](http://stackoverflow.com/questions/70324/java-inner-class-and-static-nested-class) – DimaSan Feb 25 '17 at 12:26

1 Answers1

3

Interfaces are always static when nested in a class. You should therefore access your interface declaration as A.That, not obj.That.

thrau
  • 2,915
  • 3
  • 25
  • 32
  • But we can access static member using instance,so why cannot interface? – Shubham Tyagi Feb 25 '17 at 13:36
  • If `That` was a class rather than an interface, you couldn't say `obj.That` either. You should always refer to the type as `A.That`, no matter whether it's an interface or a class, or an enum, or whatnot. – Erwin Bolwidt Feb 25 '17 at 13:56
  • "Compilable" != "preferable". Do not refer to static members through an instance. You don't need to instantiate an `A` instance here. – Lew Bloch Feb 25 '17 at 16:42