From my understanding if you implement an interface in java, the methods specified in that interface have to be used by the sub classes implementing the said interface.
Well, this topic has been adressed to ... yeah .. but think, one answer is missing. Im talking about the "Default Methods" of interfaces. For example, let's imagine you'll have a class for closing anything (like a destructor or something). Let's say it should have 3 methods. Let's call them "doFirst()", "doLast()" and "onClose()".
So we say we want any object of that type to at least realize "onClose()", but the other are optional.
You can realize that, using the "Default Methods" of interfaces. I know, this would most of the Time negate the reason of an interface, but if you are designing an framework, this can be useful.
So if you want to realize it this way, it would look the following
public interface Closer {
default void doFirst() {
System.out.print("first ... ");
}
void onClose();
default void doLast() {
System.out.println("and finally!");
}
}
What now would happen, if you for example implemented it in an class called "Test", the compiler would be perfectly fine with the following:
public class TestCloser implements Closer {
@Override
public void onClose() {
System.out.print("closing ... ");
}
}
with the Output:
first ... closing ... and finally!
or
public class TestCloser implements Closer {
@Override
public void onClose() {
System.out.print("closing ... ");
}
@Override
public void doLast() {
System.out.println("done!");
}
}
with the output:
first ... closing ... done!
All combinations are possible. Anything with "default" can be implemented, but must not, however anything without must be implemented.
Hope it is not fully wrong that i now answer.
Have a great day everybody!
[edit1]: Please note: This only works in Java 8.