Passing a method as a argument to other method in other class | Core Java Forum
K
K. Petchimuthu Pandiyan Posted on 06/10/2018
Hi all,

I have static or non static method in other class lets say class A and I need to pass this method as a parameter to other method in Class B. How can i achieve it. Can anyone please elaborate me on this. it would be great if it is explained with an example.

Regards,
Pandiyan

Y
Yogesh Chawla Replied on 08/10/2018

We need to remember one basic rule regarding accessing the static method in outer packages which is "Static methods should be accessed directly with class name"

If a class is accessible and if static method is accessible, i mean defined with correct access modifiers then that static method can be accessed anywhere within the project or ouside the project. See this example


public class ClassA {

public static void main(String[] args) {
display(); // calling without object
ClassA t = new ClassA();
t.show(); // calling using object
}

public static void display() {
System.out.println("Programming is amazing.");
}

public void show() {
System.out.println("Java is awesome.");
}
}

public class ClassB {
public static void main(String[] args) {
ClassA.display(); // calling without object
ClassA t = new ClassA();
t.show(); // calling using object
}
}