java - What is the need for having Abstract classes and interfaces separately? -


this question has answer here:

i having doubt java 8's default method feature interfaces. means java 8 can provide default implementation method in interface, no longer necessary implementing classes override method.

now interface able contain abstract method concrete method same abstract class. both behaving in same manner. talking differences between interface , abstract methods can identified - 1. multiple interfaces can implemented class, 1 class can extended. 2. interface fields public static final, while in case of abstract class have control on access modifiers of fields , methods.

my doubt difference comes picture, whether should go abstract class or interface? actual purpose having both abstract class , interface separately?

in java 8 differences between abstract class , interface have become more narrow. there still remains differences between them. try point out differences. if miss please let me know.

  1. you can create property kind of encapsulation(public, private or protected) , state(final or non-final) abstract class. property in interface has public , final.
  2. you can extend 1 abstract class implements more 1 interfaces.
  3. you can create constructor in abstract class not in interface.
  4. you can associate state abstract class interface preferred stateless situations.

you can find oracle doc here on topic.

virtual extension methods/ default methods/defender methods of interface main reason of narrow difference. try describe necessity of introducing these types of methods in java 8.

in java 8 lambda has been introduced. take full advantage of lambda collection framework has been updated. foreach method has been added in iterable interface. not feasible change interface without breaking implementation. default method used add functionality without breaking implementation.

@functionalinterface public interface iterable<t> {     iterator<t> iterator();      default void foreach(consumer<? super t> action) {         objects.requirenonnull(action);         (t t : this) {             action.accept(t);         }     } } 

i have added code snapshot here demonstrate usability of default method. think have choose between abstract class , interface based on needs.


Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -