Sunday, May 23, 2021

Java 8: Default and Static Methods in Interfaces

  • Java 8 allows the interfaces to have default and static methods
  • Default Methods
    • The reason we have default methods in interfaces is to allow the developers to add new methods to the interfaces without affecting the classes that implements these interfaces.
    • If there are 2 interfaces (multiple inheritance problem) with same default method then class MUST implement the method else it will result in compile error
    • In addition, if class also extends a class which defines same method as that of default method in interfaces then priority goes to class method
    • If interface default method is one of the Object class defined method then it will result in compile time error
  • Static Methods
    • Static methods in interfaces are similar to the default methods except that we cannot override these methods in the classes that implements these interfaces
    • We need static methods in interfaces because, suppose you want to provide some implementation in your interface and you don’t want this implementation to be overridden in the implementing class, then you can declare the method as static
  • As we can now define static & default implementation in interface, what is difference between abstract class & interface
  • There are still a few differences between Abstract classes and Java 8 interfaces though, one of them is that abstract class can have constructor while in interfaces we can’t have constructors

No comments:

SpringBoot: Features: SpringApplication

Below are a few SpringBoot features corresponding to SpringApplication StartUp Logging ·          To add additional logging during startup...