What are the differences between abstract classes and interfaces in Java 8? -


in java there used subtle important difference between abstract classes , interfaces: default implementations. abstract classes have them, interfaces not. java 8 though introduces default implementations interfaces, meaning no longer critical difference between interface , abstract class.

so is?

as best can tell, remaining difference (besides perhaps under hood efficiency stuff) abstract classes follow traditional java single-inheritance, whereas interfaces can have multiple-inheritance (or multiple-implementation if will). leads me question -

how new java 8 interfaces avoid diamond problem?

interfaces cannot have state associated them.

abstract classes can have state associated them.

furthermore, default methods in interfaces need not implemented. in way, not break existing code, while interface receive update, implementing class not need implement it.
result may suboptimal code, if want have more optimal code, job override default implementation.

and lastly, in case diamond problem occurs, compiler warn you, , you need choose interface want implement.

to show more diamond problem, consider following code:

interface {     void method(); }  interface b extends {     @override     default void method() {         system.out.println("b");     } }  interface c extends {      @override     default void method() {         system.out.println("c");     } }  interface d extends b, c {  } 

here compiler error on interface d extends b, c, that:

interface d inherits unrelated defaults method() form types b , c

the fix is:

interface d extends b, c {     @override     default void method() {         b.super.method();     } } 

in case wanted inherit method() b.
same holds if d class.

to show more difference between interfaces , abstract classes in java 8, consider following team:

interface player {  }  interface team {     void addplayer(player player); } 

you can in theory provide default implementation of addplayer such can add players example list of players.
wait...?
how store list of players?
answer cannot in interface, if have default implementations available.


Comments

Popular posts from this blog

java - WrongTypeOfReturnValue exception thrown when unit testing using mockito -

php - Magento - Deleted Base url key -

android - How to disable Button if EditText is empty ? -