javainterfacelocal-class

Java local classes and interfaces


I was wondering if the next thing is possible for implementation:

Lets say I've got 2 interfaces while each one of them has 1 function header. For example, iterface1 has function g(...) and interface2 has function f(...)

Now, I make a class and declaring that this class is implementing these 2 interfaces. In the class I try doing the next thing:

I start implementing function g(...) and in it's implementation I make a local class that implements interface2 and I add to this class the implementation of f(...).


Solution

  • I'm not quite sure what you mean. I am picturing something like this:

    interface Interface1
    {
        public void g();
    }
    
    interface Interface2
    {
        public void f();
    }
    
    class MyClass implements Interface1, Interface2
    {
        @Override
        public void g()
        {
            class InnerClass implements Interface2
            {
                @Override
                public void f()
                {
                }
            }
        }
    }
    

    Is that what you meant?

    In this case, the answer is no. The inner class (InnerClass) works fine, but it doesn't count as an implementation of f for the outer class. You would still need to implement f in MyClass:

    MyClass.java:11: MyClass is not abstract and does not override abstract method
    f() in Interface2