user550413
user550413

Reputation: 4819

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(...).

Upvotes: 2

Views: 2079

Answers (3)

mgiuca
mgiuca

Reputation: 21377

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

Upvotes: 4

Jim Blackler
Jim Blackler

Reputation: 23179

Yes, it's legal. In the example you've given, your class should implement all methods of both interfaces, and your local class should implement all methods of interface2.

Upvotes: 1

Simon G.
Simon G.

Reputation: 6717

Yes it is legal. However a class does not implement an interface because an inner class implements it. The class must implement the interface explicitly or declare itself as abstract.

Upvotes: 2

Related Questions