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?
In This Oracle tutorial I got "You cannot declare member interfaces in a local class." because "interfaces are inherently static."
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With