Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't my class implement an interface declared inside it?

I just encountered a behavior I first thought it was a bug in Eclipse. Consider this simple class:

public class Foo {
    public static interface Callback {
        public void onAction();
    }
}

This is perfectly valid. However, this isn't:

public class Foo implements Callback {
    public static interface Callback {
        public void onAction();
    }

    public void onAction() { /*some implementation*/ }
}

But this is valid, too:

public class Foo {
    public static interface Callback {
        public void onAction();
    }

    private final Callback mCallback = new Callback() {
        public void onAction() { /*some implementation*/ }
    };
}

Why does Java force me to kind of 'waste' a member for it, if it could simply save it by letting me implement this itself? I'm well aware of the 'workaround' to put this interface in its own file, but out of curiosity: Is there a reason why this won't work?

like image 449
Rafael T Avatar asked Feb 12 '13 15:02

Rafael T


People also ask

Why is it not allowed to declare an interface within a class?

In This Oracle tutorial I got "You cannot declare member interfaces in a local class." because "interfaces are inherently static."

Can an interface be declared inside a class?

Yes, you can define an interface inside a class and it is known as a nested interface. You can't access a nested interface directly; you need to access (implement) the nested interface using the inner class or by using the name of the class holding this nested interface.

How do you implement an interface inside class?

To declare a class that implements an interface, you include an implements clause in the class declaration. Your class can implement more than one interface, so the implements keyword is followed by a comma-separated list of the interfaces implemented by the class.

Why is an interface not implemented?

It means that you should try to write your code so it uses an abstraction (abstract class or interface) instead of the implementation directly. Normally the implementation is injected into your code through the constructor or a method call.


2 Answers

Using this code

public class Foo implements Callback{

public static interface Callback{
    public void onAction()
}

public void onAction(){//some implementation}
}

what is Callback ? The compiler (btw which is different from Eclipse, ) doesn't know what is Callback.

You defined the Callback interface after you used it.

like image 117
banuj Avatar answered Oct 17 '22 06:10

banuj


In your 2nd case, since the signatures are checked before the bodies of the classes, when the compiler tries to compile the Foo class, the Callback interface isn't defined yet.

like image 36
sp00m Avatar answered Oct 17 '22 07:10

sp00m