Using Method References in java 8 part 2:

     First two method references are explained in part 1. The link is given below.

https://rajeeva84.blogspot.com/2024/09/using-method-references-in-java8-part-1.html

Remaining two types are briefly described below.

3.Instance references of a particular object:

              This method reference deals with a particular object within  the class. To implement this method, use the below code.

        Class  Object = inst:: memberFunction;

 Steps:

  • ·       As a beginning, create an interface “Sample” with a void function abc().
  • ·       Inside the class InstMethodReference, develop the code for Message().
  • ·       In the main function, create an object for the class and using “inst::” to call the instance reference of the object created.

// Java Program to develop instant reference of particular object.

interface Sample {

    void abc();

}

public class InstMethodReference {

    public void Message() {

        System.out.println("This is an instance reference of particular object");

    }

    public static void main(String[] args) {

        InstMethodReference inst = new InstMethodReference();

        Sample s = inst::Message;

        s.abc();

    }

}

After the code completion, just compile and run the code as follows.

C:\raji\blog>javac InstMethodReference.java

C:\raji\blog>java InstMethodReference

This is an instance reference of particular object

 

4.Instance Method References of an Arbitrary Object of a Particular Type:

              This type of method reference deals with arbitrary object.

Steps:

  • ·       Create a class “OtherObjectMethodReference”. Inside main(), create a list “plang” and assign different programming languages.
  • ·       Using foreach method, print the list.

import java.util.Arrays;

import java.util.List;

public class OtherObjectMethodReference {

    public static void main(String[] args) {

        List<String> plang = Arrays.asList("C", "C++", "Java");

        plang.forEach(System.out::println);

    }

}

Final step is compile and run the program.

C:\raji\blog>javac OtherObjectMethodReference.java

C:\raji\blog>java OtherObjectMethodReference

C

C++

Java

These are the ways to implement method references in java8.

No comments:

Post a Comment