In Java, calling a function/method from another class allows the programmer to reuse the code multiple times. This helps to avoid applying the same functionalities repeatedly. Moreover, this approach assists in linking the complex codes. In inheritance, this method call is usually required by the subclass to apply the superclass features.
How to Call/Invoke a User-Defined Java Method From Another Class?
Consider the following scenario to call a method from another class in Java:
Query: Let’s assume there is a method named “printID()” in the class “IDDetail” that needs to be called in another class named “Methodcall”.
Solution: In the “Methodcall” class, create an object of the class “IDDetail” from which the method “printID()” needs to be called. After that, invoke this method using the created class object.
Note: The process of calling the “static” and “private” methods are different. It is such that the “static” method is invoked directly from another class using the class name while the “private” method, however, is invoked using the “reflection API”.
Example 1: Invoking a Default Method From Another Class
The stated method is the one that doesn’t contain any access modifier. This method can only be accessed/invoked from within the package.
The following example calls a default method from another class using the method’s(called) class instance:
package jbArticles;
class IDDetail {
void printID() {
System.out.println("Student ID: " +1);
}
}
public class Methodcall {
public static void main(String[] args) {
IDDetail ob = new IDDetail();
ob.printID();
}}
Code Explanation
- Declare the class “IDDetail” that defines the default method “printID()” having the given message.
- In the class “Methodcall”, create an instance/object of the class “IDDetail” using the “new” keyword and the “IDDetail()” constructor.
- Lastly, call the method of the “IDDetail” class using the class object.
Output
In the code output, it is clear that the default method “printID()” is called using the class instance appropriately.
Example 2: Invoking a Public Method From Another Class
The “public” method has a wider scope and can be called/accessed within the package as well as from outside the package. In this example, a “public” method will be called from another class using the object of that class:
package jbArticles;
class IDDetail {
public void printID() {
System.out.println("Student ID: " +1);
}
}
public class Methodcall {
public static void main(String[] args) {
IDDetail ob = new IDDetail();
ob.printID();
}}
Code Explanation
Declare the class “IDDetail” and define the public method “printID()”. In the “Methodcall” class, create an object of the “IDDetail” class and call its method “printID()” in this class using the class object.
Output
Example 3: Invoking a Protected Method From Another Class
The stated method can be called/invoked in the other class if that class is a subclass of the class containing the “protected” method:
package jbArticles;
class IDDetail {
protected void printID() {
System.out.println("Student ID: " +1);
}
}
public class Methodcall extends IDDetail{
public static void main(String[] args) {
IDDetail ob = new IDDetail();
ob.printID();
}}
Code Explanation
- In the declared “IDDetail” class, define a “protected” method named “printID()”.
- Now, create another class “Methodcall” and make it a subclass of the “IDDetail” class using the “extends” keyword.
- In this class, similarly, create an object of the “IDDetail” class(containing the “protected” method) and call its method using its class object.
Output
Here, it can be observed that the “protected” method is called successfully by making the “Methodcall” a subclass of the “IDDetail” class.
Example 4: Invoking a Static Method From Another Class
This method can be called/invoked via the class name without creating a class instance/object. In this demonstration, a “static” method can be called from another class:
package jbArticles;
class IDDetail {
static void printID() {
System.out.println("Student ID: " +1);
}
}
public class Methodcall {
public static void main(String[] args) {
IDDetail.printID();
}}
Code Explanation
In the declared “IDDetail” class, create a static method “printID()”. Define another class “Methodcall” in which the method “printID()” is called using the class name in which it is defined.
Output
The method “printID()” is invoked directly in the “Methodcall” class from the “IDDetail” class.
Calling/Invoking a Private Method From Another Class
A “private” method has many restrictions while accessing it from another class. However, it can be accessed and called from another class using “reflection API”. This API modifies the behavior of a class at runtime.
The following code calls a private method from another class by including the “java.lang.reflect.Method” library and applying the “getDeclaredMethod()”, “setAccessible()” and “invoke()” methods, as demonstrated below:
package jbArticles;
import java.lang.reflect.Method;
class IDDetail {
private void printID() {
System.out.println("Student ID: " +1);
}}public class Methodcall {
public static void main(String[] args) throws Exception {
IDDetail ob = new IDDetail();
Method x = IDDetail.class.getDeclaredMethod("printID");
x.setAccessible(true);
x.invoke(ob);
}}
Code Explanation
- Import the given library to use the “reflection API”.
- Recall the steps to define the class “IDDetail”.
- In the next step, create a private method “printID()”.
- In the other class i.e., “Methodcall”, create an instance of the “IDDetail” class.
- Now, apply the “getDeclaredMethod()” to get the Method object for the specified method of the “IDDetail” class.
- After that, use the “setAccessible()” method to set the accessible object for the flag.
- Lastly, the “invoke()” method calls the method reflected by the Method object.
Output
Here, it can be verified that the “private” method is called from the “IDDetail” class with the help of “reflection API”.
Calling/Invoking a Private Method From Another Class via the Inheritance
In inheritance, a method of the parent class can also be called from its subclass, demonstrated below:
package jbArticles;
class IDDetail {
public void printID() {
System.out.println("Student ID: " +1);
}}
class Child extends IDDetail{
public void displayName() {
printID();
System.out.println("Student Name: David");
}
}
public class Methodcall {
public static void main(String[] args) throws Exception {
Child ob = new Child();
ob.displayName();
}}
Code Explanation
- Declare a parent class “IDDetail” having the method “printID()”.
- Inherit a class named “Child” from the parent class via the “extends” keyword.
- In this class, define the method “displayName()” that contains the invoked “printID()” method from the parent class and the given statement.
- Create an object of the “Child” in the “main” method and invoke its method via the created object.
Output
Upon calling the subclass method, the called “printID()” method’s implementation from the parent class is also returned accordingly.
How to Call the “main()” Method From Another Class in Java?
Calling the “main()” method is tricky as it can result in various errors if used in the wrong way. The following points should be considered while calling the “main()” method:
- The “main()” method should be invoked from a “static” method only within the same class.
- This method should be passed as “String[] args” while calling it.
- Invoking the “main()” method directly leads to an infinite loop since the memory stack knows to execute only the “main()” method.
Below is the code demonstration that calls the “main()” method from another class considering all the above-discussed points by specifying a counter value:
package jbArticles;
class Methodcall {
static int counter = 0;
static void mainInvoke(){
counter++;
if (counter <= 2) {
main(null);
}
}
public static void main(String[] args){
System.out.println("Calling the main() Method");
mainInvoke();
}}
Code Explanation
- Define the class “Methodcall” having the initialized counter value and the “mainInvoke()” method.
- In this method definition, increment the counter value till “2” and call the “main()” method by passing “null” as its argument.
- In the “main()” method, print the given statement and invoke the “mainInvoke()” method that calls the “main()” method from that class.
Output
The “main()” method is called appropriately from another class and the specified message is printed according to the counter value.
Conclusion
To call/invoke a user-defined method from another Java class, create an object of the class containing the method and call/invoke the particular method via the created object. However, the “static” methods are invoked directly via class name, and “private” methods are called using “reflection API”. This calling varies from method to method i.e., default, public, protected, static, private.