How to Call a Method From Another Class in Java

In object-oriented programming, classes are the blueprints for creating objects. These blueprints define the state and behavior that the objects created from them will have. Java, being an object-oriented language, allows objects to interact with each other through methods. One common operation is calling a method from another class. This can be achieved in a couple of ways, depending on whether the method is static or non-static. In this blog post, we will explore both scenarios with examples.

Calling a Non-Static Method

Non-static methods belong to an instance of a class. To call a non-static method from another class, you first need to create an instance (object) of the class to which the method belongs.

Example

Let's consider a simple example with two classes: Greeting and MainApp.

Greeting.java
public class Greeting {
    public void sayHello(String name) {
        System.out.println("Hello, " + name + "!");
    }
}
MainApp.java
public class MainApp {
    public static void main(String[] args) {
        Greeting greeting = new Greeting(); // Creating an instance of Greeting
        greeting.sayHello("Java Learner"); // Calling the non-static method
    }
}
Output:
Hello, Java Learner!
In this example, the sayHello method is a non-static method inside the Greeting class. To call this method, the MainApp class first creates an instance of Greeting using new Greeting() and then calls the method on that instance. 

Calling a Static Method 

Static methods belong to the class itself rather than any instance of the class. This means you can call a static method without creating an object of the class. 

Example 

Let's modify our Greeting class to include a static method. 

Greeting.java
public class Greeting {
    public static void sayStaticHello(String name) {
        System.out.println("Static Hello, " + name + "!");
    }
}
MainApp.java
public class MainApp {
    public static void main(String[] args) {
        Greeting.sayStaticHello("Static Java Learner"); // Calling the static method
    }
}
Output:
Static Hello, Static Java Learner!
In this case, sayStaticHello is a static method. We call it directly on the class (Greeting.sayStaticHello) without needing to create an instance of Greeting

Conclusion 

Understanding how to call methods from another class is fundamental in Java and OOP. It allows for the creation of modular, reusable code. By practicing with examples like the ones provided, you can become more comfortable with both non-static and static methods and how to use them effectively in your Java applications.

Comments