Monday 3 October 2022

Java 8 Features

1)Lambda expression/function: is an anonymous function that can be passed around where anonymous means that it does not have name .It is function as it is not associated with class like method. Passed around means it can passed as an argument to a method or can be stored in a variable.

Usage ::

Used to represent the instance of the functional interface.

syntax is as follows:

             (a,b)->System.out.println(a+b);

 Advantage ::

   No boiler plate code for simple things.

 

2)Functional interface: is an interface which contains only one abstract method but can have any number of default methods.

@FunctionalInteface

public interface Predicate{

boolean test(T t);

}


@FunctionalInterface

public interface Consumer {

void accept(T t);

}


@FunctionalInterface

public interface Function{

 public R apply(T t); 

}


@FunctionalInterface

public interface Supplier{

 public T get();

}


3)Default method inside Interface :

public interface MyInterface { // regular interface methods default void defaultMethod() { // default method implementation } }

In a typical design based on abstractions, where an interface has one or multiple implementations, if one or more methods are added to the interface, all the implementations will be forced to implement them too. Otherwise, the design will just break down.

Default interface methods are an efficient way to deal with this issue. They allow us to add new methods to an interface that are automatically available in the implementations. Therefore, we don't need to modify the implementing classes.

In this way, backward compatibility is neatly preserved without having to refactor the implementers.

what happens when a class implements several interfaces that define the same default methods.

In that case, the code simply won't compile, as there's a conflict caused by multiple interface inheritance (a.k.a the Diamond Problem). 

To solve this ambiguity, we must explicitly provide an implementation for the methods by overriding the implementation in class.


@Override public String turnAlarmOn() { return Vehicle.super.turnAlarmOn(); } @Override public String turnAlarmOff() { return Vehicle.super.turnAlarmOff(); }


4)static method inside Interface

5)Predicate<T> : has test method returns boolean

6)Function <T,R> : has apply method return R type after applying some business logic.

7)Consumer<T> : has accept method and it does not return anything instead can be used for iteration.

8)Supplier< > : has get Method and it returns  T type object.

9)Method reference and constructor reference by using :: (double colon ) operator.

10)Streams

11)Date & Time API (Joda API) 





No comments:

Post a Comment