How To Call Method In Another Class Java

8 min read

Calling a method defined in a different class is a fundamental concept in Java, serving as the backbone of object-oriented programming. It enables code reusability, modularity, and the separation of concerns, allowing developers to build complex applications from manageable, independent components. Whether you are accessing a utility function, interacting with a service layer, or manipulating an entity object, understanding the mechanics of cross-class method invocation is essential for writing clean, efficient Java code.

Understanding the Basics: Instance vs. Static Context

Before diving into syntax, it is critical to distinguish between the two primary types of methods in Java: instance methods and static methods. The way you call them differs significantly because of how they exist in memory.

Calling Instance Methods

An instance method belongs to a specific object (instance) of a class. In real terms, it operates on the instance variables (state) of that specific object. Worth adding: to call an instance method from another class, you must first create an object of that class using the new keyword, then use the dot operator (. ) on that object reference.

Consider a simple Calculator class:

public class Calculator {
    // Instance method
    public int add(int a, int b) {
        return a + b;
    }
    
    public int multiply(int a, int b) {
        return a * b;
    }
}

To use this in a Main class:

public class Main {
    public static void main(String[] args) {
        // 1. Instantiate the class (create an object)
        Calculator myCalc = new Calculator();
        
        // 2. Call the method using the object reference
        int sum = myCalc.add(10, 5);
        int product = myCalc.multiply(4, 3);
        
        System.out.println("Sum: " + sum);       // Output: Sum: 15
        System.out.println("Product: " + product); // Output: Product: 12
    }
}

Key Takeaway: No object exists until new Calculator() runs. The method add lives inside myCalc. If you create Calculator anotherCalc = new Calculator(), it has its own separate copy of instance variables (if any existed), though the method code itself is shared in memory.

Calling Static Methods

A static method belongs to the class itself, not to any specific object. It is loaded into memory when the class is loaded. You do not need—and generally should not use—an instance to call it. Instead, you use the Class Name followed by the dot operator.

Easier said than done, but still worth knowing.

A classic example is the Math utility class or a custom StringUtils helper Turns out it matters..

public class StringUtils {
    // Static method
    public static boolean isNullOrEmpty(String str) {
        return str == null || str.trim().isEmpty();
    }
    
    public static String capitalize(String str) {
        if (isNullOrEmpty(str)) return str;
        return str.substring(0, 1).toUpperCase() + str.substring(1).toLowerCase();
    }
}

Calling from another class:

public class Main {
    public static void main(String[] args) {
        // Call directly using Class Name
        boolean check = StringUtils.isNullOrEmpty("  ");
        String formatted = StringUtils.capitalize("hello world");
        
        System.out.println("Is empty? " + check); // Output: Is empty? true
        System.out.println(formatted);             // Output: Hello world
    }
}

Best Practice: While Java technically allows calling a static method via an object reference (e.g., myCalc.add(1,2) if add were static), compilers will issue a warning. Always use ClassName.methodName() for static methods to improve readability and avoid confusion.

Access Modifiers: The Gatekeepers

You cannot call a method from another class if the access modifier restricts visibility. This is the most common compilation error beginners face.

Modifier Same Class Same Package (Subclass/Non-Subclass) Different Package (Subclass) Different Package (Non-Subclass)
public ✅ ✅ ✅ ✅
protected ✅ ✅ ✅ ❌
default (package-private) ✅ ✅ ❌ ❌
private ✅ ❌ ❌ ❌

Scenario: If Calculator had private int add(...), the Main class (assuming it's in a different package or even the same package) would fail to compile with "add() has private access in Calculator."

Design Tip: Follow Encapsulation. Keep fields private. Expose behavior via public methods. Use protected for internal inheritance hierarchies. Avoid default (package-private) unless designing a specific module API That's the whole idea..

Passing Arguments: Primitives vs. Objects

How data flows into the called method depends on the parameter type. Java is strictly Pass-by-Value, but the "value" differs for primitives and references.

Primitive Types (Pass-by-Value)

When you pass a primitive (int, double, boolean, etc.), a copy of the value is made. The original variable in the calling class remains unchanged Turns out it matters..

public class Modifier {
    public void changeValue(int number) {
        number = 20; // Modifies the local copy
        System.out.println("Inside method: " + number);
    }
}

public class Main {
    public static void main(String[] args) {
        Modifier m = new Modifier();
        int value = 10;
        m.Day to day, changeValue(value);
        System. out.

### Object References (Pass-by-Value of the Reference)
When you pass an object, you pass a **copy of the reference (memory address)**. Both the caller and the method point to the *same object* on the Heap.
*   You **can** modify the object's internal state (fields).
*   You **cannot** swap the object reference itself (make the caller's variable point to a *new* object).

```java
public class User {
    String name;
    User(String name) { this.name = name; }
}

public class Modifier {
    // 1. Modifying State (Works)
    public void rename(User u, String newName) {
        u.name = newName; // Changes the actual object's field
    }
    
    // 2. 

public class Main {
    public static void main(String[] args) {
        Modifier m = new Modifier();
        User user = new User("Alice");
        
        m.replaceUser(user);
        System.)
        
        m.out.println(user.out.name); // Output: Bob (State changed!rename(user, "Bob");
        System.println(user.

## Advanced Invocation Patterns

Beyond simple `object.Consider this: method()` or `Class. method()`, Java offers sophisticated ways to invoke methods dynamically or structurally.

### 1. Method Overloading
A class can have multiple methods with the same name but different parameter lists (signature). The compiler decides which to call at compile time based on arguments provided.

```java
public class Printer {
    public void print(int i) { System.out.println("Integer: " + i); }
    public void print(String s) { System.out.println("String: " + s); }
    public void print(double d

```java
    public void print(double d) { System.out.println("Double: " + d); }
}

public class Main {
    public static void main(String[] args) {
        Printer p = new Printer();
        p.print(42);       // Output: Integer: 42
        p.Which means print("Hello");  // Output: String: Hello
        p. Which means print(3. 14);     // Output: Double: 3.

Overloading is resolved statically. Think about it: the compiler examines the *declared* types of the arguments—not their runtime types—to select the most specific matching signature. If no exact match exists, Java widens primitives (e.g., `int` to `long` or `double`) or autoboxes them, but it never narrows automatically.

### 2. Method Overriding (Dynamic Dispatch)
While overloading is decided at compile time, overriding is resolved at **runtime**. When a subclass provides its own implementation of an inherited method, the JVM invokes the version defined by the *actual object type*, not the reference type. This is the heart of polymorphism.

```java
public class Animal {
    public void speak() { System.out.println("Some sound"); }
}

public class Dog extends Animal {
    @Override
    public void speak() { System.out.println("Woof"); }
}

public class Main {
    public static void main(String[] args) {
        Animal a = new Dog(); // Reference type Animal, object type Dog
        a.speak();            // Output: Woof (Dog's version runs)
    }
}

The @Override annotation is optional but recommended; it lets the compiler catch mistakes such as a misspelled method name that would otherwise silently create an overload instead of an override.

3. Method Chaining

Methods can return an object (often this) to allow calls to be chained in a single fluent expression. The StringBuilder class is the classic example Not complicated — just consistent..

public class Builder {
    private final StringBuilder sb = new StringBuilder();

    public Builder append(String s) {
        sb.append(s);
        return this; // Enables chaining
    }

    public String build() { return sb.toString(); }
}

public class Main {
    public static void main(String[] args) {
        String result = new Builder()
            .Also, append("Java ")
            . But append("is ")
            . In practice, append("expressive")
            . build();
        System.out.

### 4. Method References and Higher-Order Functions
Since Java 8, methods themselves can be treated as values through **method references** (`::`) and lambdas. This allows a method to be passed as an argument to another method, enabling functional-style invocation.

```java
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List names = List.of("Alice", "Bob", "Charlie");

        // Static method reference
        names.forEach(System.out::println);

        // Instance method reference
        names.forEach(String::toUpperCase);

        // Lambda invoking a method per element
        names.Also, stream()
             . filter(name -> name.On the flip side, startsWith("B"))
             . forEach(System.

### 5. Reflection
At the most dynamic end of the spectrum, the `java.lang.reflect` API allows a program to inspect and invoke methods by name at runtime—even private ones. This is powerful but bypasses compile-time safety, so it should be used sparingly.

```java
import java.lang.reflect.Method;

public class Main {
    public static void main(String[] args) throws Exception {
        String target = "hello";
        Method method = String.On the flip side, invoke(target); // Invokes by reflection
        System. class.getMethod("toUpperCase");
        Object result = method.out.

## Choosing the Right Pattern

Each invocation mechanism serves a distinct purpose:

*   **Overloading** improves readability by grouping related operations under one name.
*   **Overriding** provides behavioral flexibility through polymorphism.
*   **Chaining** produces concise, readable construction code.
*   **Method references** express intent declaratively and integrate with the Streams API.
*   **Reflection** enables frameworks and libraries, but trades safety for flexibility.

## Conclusion

Method invocation in Java is far richer than the familiar `object.The language carefully distinguishes between *value semantics* for primitives and *reference semantics* for objects, ensuring predictable behavior when arguments are passed. method()` syntax suggests. On top of this foundation, Java layers multiple dispatch strategies: static resolution for overloaded methods, dynamic dispatch for overridden ones, and progressively more flexible mechanisms ranging from fluent chaining to functional method references and runtime reflection.

Understanding these patterns lets you write code that is not only correct but expressive. Choosing pass-by-value semantics wisely prevents surprising side effects, and selecting the appropriate invocation style—compile-time
Fresh Picks

Freshly Published

Others Went Here Next

More of the Same

Thank you for reading about How To Call Method In Another Class Java. We hope the information has been useful. Feel free to contact us if you have any questions. See you next time — don't forget to bookmark!
⌂ Back to Home