Java Interface 8

11

Java 8 allows you to implement methods in the interface itself.

So I would like to know what an abstract class can do that an interface can not.

Source: link

    
asked by anonymous 01.10.2015 / 22:25

1 answer

10

Abstract classes can contain state and interface can not. This is the main justification for using it from a more technical point of view. Obviously because it has been, it may have constructors, not interface.

Another reason is the possibility of having private members. Interfaces can only have public methods.

From a conceptual point of view the abstract class still gets the idea that the derived object is a base object. The interface continues to convey the idea that the object using the interface only has a specific behavior.

Remembering that it was always more interesting to create interfaces than abstract classes as much as possible.

That is, it does not change anything, unless you automated the process of using the interface a bit. You will not pass using interfaces where you needed to use an abstract class. Unless he wore abstract class where he should not. Improved interface usage. It has not changed the use case for each of the mechanisms.

Until Java 7, the concrete method that complies with the interface contract needed to be written to the class. There were cases that this could lead to duplication of code. To avoid duplication the solution was to create a utility class (called companion class ) with implementation. Then inside the method in the concrete class that implements the interface it was only to call the utility method of this class of companion.

In Java 8, you do not have to do this. The method is already written inside the interface and in the concrete class does not have to write anything, the class already knows what to execute. Obviously the utilitarian class is no longer necessary. It facilitates code reuse and improves encapsulation.

Note that nothing prevents you from implementing something different and overriding the default implementation of the interface. And obviously it is necessary to implement the concrete method, creating a disambiguation, if there is more than one interface requiring the same method (same signature)

"Official" documentation for default methods .

Related: Java 8 "default method" versus C # "extend method"

    
01.10.2015 / 22:38