instagram

Method references in java 8

Method references in java 8

In java 8 we can pass method references. In this article I am going to explain how to pass static and instance method reference.

:: is use for passing a method reference to another method call.

Example Code :

In this example we are going to create one interface and two classes.

Car interface with one abstract method printColor(String s)

@FunctionalInterface
public interface Car {
	
	public void printColor(String s);	
	
}

Animal class with one instance method printAnimalColor(String color).

public class Animal {

	public void printAnimalColor(String color){
		System.out.println("Animal Color is : "+color);
	}
	
}

Now Main class

public class Main {

	public static void main(String[] args) {

		Animal animal = new Animal();
		Main main = new Main();
		main.printIt(Main::printString);
		main.printIt(animal::printAnimalColor);

	}

	public static void printString(String s) {
		System.out
				.println("This is call  passing a method reference to another method call. String is : "
						+ s);
	}

	public Car printIt(Car car) {
		car.printColor("WHITE");
		return car;
	}

}

Output:

This is call passing a method reference to another method call. String is : WHITE
Animal Color is : WHITE

Again in above code :: is use for passing a method reference to another method call.

<LEFT SIDE - CLASS OR INSTANCE > :: <RIGHT - METHOD NAME>

In line number 7 main.printIt(Main::printString); we are passing static method reference.
In line number 8 main.printIt(animal::printAnimalColor); we are passing instance method reference.

If you notice then you will find one common thing in above code. It’s method signature. All three methods have same signature.

Car Interface have : public void printColor(String s);
Animal class have : public void printAnimalColor(String color):
Main have static method : public static void printString(String s);

It means in public Car printIt(Car car), It requires implementation of Car interface and compiler will do it for us, We just need to pass reference of non abstract method which has same signature as Car‘s public void printColor(String s);

Share
1 Comment

Comments are closed.