Method Referencing in Java 8 or Above

Dr. Vipin Kumar
1 min readJan 27, 2021

Method References

The mapping of Function Interface method to the specified method by using “::” (double colon) operator is called Method Referencing. This specified method can be either a static or instance method. But there is a condition, Functions Interface method and specified method should have same argument types, except this the remaining things like return type, method name, access modifier is not required to match.

The syntax for Method References:

A) If a specified method is a static method:

Classname::methodName

B) If a specified method is an instance method:

Objectname::methodName

Let’s understand with an example:

@FunctionalInterface

interface Message

{

public abstract void msg();

}

class DisplayMessage

{

public void display()

{

System.out.println(“This is method references example”);

}

public static void display2()

{

System.out.println(“This is method references example”);

}

}

public class Test

{

public static void main (String [] args)

{

DisplayMessage dm = new DisplayMessage();

Message m1 =dm::display();

m1.msg();

Message m2 =DisplayMessage::display2();

m2.msg();

}

}

Constructor References

The mapping of the constructor to the specified method by using “::” (double colon) operator is called Constructor Referencing.

The syntax for Constructor References:

Classname::new

Let’s understand with an example:

@FunctionalInterface

interface Message

{

public abstract void msg ();

}

class DisplayMessage

{

public DisplayMessage()

{

System.out.println(“This is method references example”);

}

}

public class Test

{

public static void main (String [] args)

{

Message m1 =DisplayMessage::new;

m1.msg();

}

}

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Dr. Vipin Kumar
Dr. Vipin Kumar

Written by Dr. Vipin Kumar

Assoc. Prof. , DCA & Assoc. Head (SD), SDFS, at KIET, PhD (CS) My YouTube Channel: Dr. Vipin Classes (https://www.youtube.com/channel/UC-77P2ONqHrW7h5r6MAqgSQ)

No responses yet

Write a response