0

For below code,

interface SuperInterface{
    void f();
    interface StaticNestedInterface{    
    }
}

class Sub implements SuperInterface{
    public void f(){

    }
}

public class Dummy {

    public static void main(String[] args) {
        Sub x  = new Sub();
    }

}

Compiler does not ask class Sub to implement interface StaticNestedInterface.

Is class Sub a valid java code?

overexchange
  • 15,768
  • 30
  • 152
  • 347
  • 2
    If it compiles, it's valid. The nested interface is still just another interface, it's name is just qualified by the outer interface. – Andreas Sep 05 '15 at 05:11

3 Answers3

1

Yes, its a valid Java code. You are just declaring StaticNestedInterface in SuperInterface. One way to use nested interface would be

interface SuperInterface {
    void f();

    StaticNestedInterface sni();

    interface StaticNestedInterface {
        void a();
    }
}


class Sub implements SuperInterface{
    public void f(){

    }

    @Override
    public StaticNestedInterface sni() {
        return null;
    }
}
novic3
  • 106
  • 5
  • Is `StaticNestedInterface` like just declaring nested user defined datatype? – overexchange Sep 05 '15 at 05:35
  • Yes, ```interface``` is similar to ```class``` in this case. When you declare ```StaticNestedInterface```, it becomes available for anyone to use. You still need to put a method in the ```SuperInterface``` for classes to implement. Super and nested interface would not behave any differently than two independent interfaces. This is because, unlike classes, interface cannot be private/protected. – novic3 Sep 05 '15 at 05:50
  • two independent interfaces, you mean similar to package and subpackage concept. – overexchange Sep 05 '15 at 05:57
  • packages does not affect ```interface``` usages. You could keep them anywhere in your project. I meant two independent interfaces as in defined anywhere in separate java files. – novic3 Sep 05 '15 at 06:18
0

Yes its a valid java code. Java compiler will create public static SuperInterface$StaticNestedInterface{}

To use the nested interface class Sub implements SuperInterface.StaticNestedInterface then compiler will ask Sub class to implement the method declared on StaticNestedInterface

KSTN
  • 2,002
  • 14
  • 18
-1
interface StaticNestedInterface{    
  void a();
  void b();
}

interface SuperInterface extends StaticNestedInterface{
    void f();
}
class Sub implements SuperInterface{
    //now compiler require all methods(a, b and f)
}
Oleh Kurpiak
  • 1,339
  • 14
  • 34
  • In your answer, `StaticNestedInterface` is actually not nested interface, it is parent of `SuperInterface`. – overexchange Sep 05 '15 at 05:20
  • @overexchange, you want to implement both interfaces, so you need to like this, or in the definition of class implement both interfaces – Oleh Kurpiak Sep 05 '15 at 05:22