Tuesday, 24 November 2020

JDK 18 - Understanding Functional Interface

 What is Functional Interface?

Functional Interfaces: An interface is called a functional interface if it has a single abstract method irrespective of the number of default or static methods.

  • Annotation @FunctionInterface used(optional).
  •  It should have only 1 abstract method.
  • Two abstract methods give compilation error(given annotation is written @FunctionalInterface).
  • It can have any number of default or static methods.

Why it is used and what are the benefits?
  • Earlier we used to use Anonymous class to serve the purpose of inline method implementation. This approach with an anonymous class is tedious, lengthy, and not easy to read.
  • Functional Interface helps us achieve the same benefit of anonymous class but in a concise form.

Below is the example of Anonymous class and functional interface serving the same purpose.

FunctionalInterfaceImpl


AnonymouseClassDemo


FunctionalInterfaceDemo


As we can see from the above examples, to implement different behavior of doOperation method, Lamda expression approach looks more concise and easy to read than Anonymous Class.








Tuesday, 5 September 2017

Static, instance blocks in Java

Static and Instance Block

Static and non-static blocks are more of the same in syntax. A block can be static if we write a static keyword before the block.



Static Block:

  • java's static block is a group of statements that gets executed when the class gets loaded by ClassLoader
  • It is generally used to create static resources when the class is loaded.
  • static block code gets only once at the time of class loading
  • static blocks always gets executed first, We can have multiple static blocks, but it doesn't make much sense
  • static block can't access non-static variables and methods.

Non-Static/ Instance Block:
  • Instance block will get executed on each object creation but,  before the constructor. 
  • It can access static as well as non-static variables and methods