Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding methods or not adding methods to interface?

In Java 8, we can have default implementations for methods in interfaces, in addition to declarations which need to be implemented in the concrete classes.

Is it a good design or best practice to have default methods in an interface, or did Java 8 come-up with that only to provide more support on older APIs? Should we start with using default methods in new Java 8 projects?

Please help me to understand what is good design here, in detail.

like image 832
Kathiresa Avatar asked Sep 05 '16 12:09

Kathiresa


People also ask

Is it necessary to implement all methods in an interface?

Yes, it is mandatory to implement all the methods in a class that implements an interface until and unless that class is declared as an abstract class. Implement every method defined by the interface.

Can we add methods in interface?

So in Java 8 you can add a default method implementation into interface so all classes that implemented old version of "A" will not be broken but will fall back on default implementation.

Can you write an interface without any methods?

Yes, you can write an interface without any methods. These are known as marking interfaces or, tagging interfaces. A marker interface i.e. it does not contain any methods or fields by implementing these interfaces a class will exhibit a special behavior with respect to the interface implemented.

What is the advantages of methods in interface?

Avoiding code duplication. Ensuring code re-usability. Improving code readability.


1 Answers

Prior java8, you were looking towards versioned capabilities when talking about "reasonable" ways of extending interfaces:

You have something like:

interface Capability ...

interface AppleDealer {
  List<Apples> getApples();
}

and in order to retrieve an AppleDealer, there is some central service like

public <T> T getCapability (Class<T> type);

So your client code would be doing:

AppleDealer dealer = service.getCapability(AppleDealer.class);

When the need for another method comes up, you go:

interface AppleDealerV2 extends AppleDealer { ...

And clients that want V2, just do a getCapability(AppleDealerV2.class) call. Those that don't care don't have to modify their code!

Please note: of course, this only works for extending interfaces. You can't use this approach neither to change signatures nor to remove methods in existing interfaces.

Thus: just adding a new method to an interface; and having default to implement that method right there; without breaking any existing client code is a huge step forward!

Meaning: why wouldn't you use default methods on existing interfaces? Existing code will not care. It doesn't know about the new defaulted methods.

like image 83
GhostCat Avatar answered Oct 14 '22 14:10

GhostCat