Calling a method from another class is a fundamental concept in Java that enables code reusability, modularity, and the implementation of object-oriented principles like encapsulation and separation of concerns. That's why whether you are building a small utility tool or a large-scale enterprise application, understanding the different ways to invoke methods across classes is essential for writing clean, maintainable, and efficient code. This guide explores the various mechanisms—static calls, instance calls, constructors, and advanced patterns—providing clear examples for each scenario The details matter here..
Understanding the Basics: Static vs. Instance Methods
Before diving into the syntax, it is crucial to distinguish between the two primary types of methods in Java: static methods and instance methods. The way you call them differs significantly because of how they are bound to the class structure Easy to understand, harder to ignore..
Calling Static Methods
Static methods belong to the class itself rather than any specific object instance. Because of that, they are often used for utility functions, helper operations, or factory methods. Because they are class-level members, you do not need to create an object to invoke them.
To call a static method from another class, use the class name followed by the dot operator and the method name.
// UtilityClass.java
public class UtilityClass {
public static int add(int a, int b) {
return a + b;
}
public static String greet(String name) {
return "Hello, " + name + "!";
}
}
// MainClass.java
public class MainClass {
public static void main(String[] args) {
// Calling static methods using ClassName.greet("Developer");
System.println("Sum: " + sum); // Output: Sum: 30
System.methodName()
int sum = UtilityClass.out.On top of that, add(10, 20);
String message = UtilityClass. out.println(message); // Output: Hello, Developer!
**Key Points for Static Calls:**
* **Syntax:** `ClassName.methodName(arguments)`
* **Access Modifiers:** The method must be `public` (or package-private if in the same package) to be accessible.
* **Imports:** If the class is in a different package, you must import it (`import packageName.UtilityClass;`) or use the fully qualified name.
### Calling Instance Methods
Instance methods (non-static methods) belong to an object instance. They operate on the state (fields) of that specific object. To call an instance method, you must first **instantiate the class** using the `new` keyword (or a factory method) to create an object reference.
```java
// Calculator.java
public class Calculator {
private int lastResult; // Instance variable (state)
public int multiply(int a, int b) {
lastResult = a * b;
return lastResult;
}
public int getLastResult() {
return lastResult;
}
}
// MainClass.Instantiate the class (Create an object)
Calculator myCalc = new Calculator();
// 2. println("Product: " + product); // Output: Product: 30
System.multiply(2, 2);
// myCalc's state remains unchanged
System.Also, println("Last Result: " + myCalc. Call instance method using objectReference.getLastResult()); // Output: Last Result: 30
// Creating a second independent instance
Calculator anotherCalc = new Calculator();
anotherCalc.Even so, out. methodName()
int product = myCalc.multiply(5, 6);
System.out.out.Plus, java
public class MainClass {
public static void main(String[] args) {
// 1. println("MyCalc Last Result: " + myCalc.
**Key Points for Instance Calls:**
* **Syntax:** `objectReference.methodName(arguments)`
* **State Management:** Each object maintains its own copy of instance variables.
* **Null Safety:** Ensure the object reference is not `null` before calling methods to avoid `NullPointerException`.
## Access Modifiers and Visibility
The ability to call a method from another class is governed by Java’s access control modifiers. If a method is not visible, the compiler will throw an error.
| Modifier | Same Class | Same Package (Subclass/Non-Subclass) | Different Package (Subclass) | Different Package (Non-Subclass) |
| :--- | :---: | :---: | :---: | :---: |
| **public** | ✅ | ✅ | ✅ | ✅ |
| **protected** | ✅ | ✅ | ✅ | ❌ |
| **default (package-private)** | ✅ | ✅ | ❌ | ❌ |
| **private** | ✅ | ❌ | ❌ | ❌ |
**Best Practice:** Favor `private` for internal helper methods and `public` only for the API you intend to expose. Use `protected` sparingly, typically when designing for inheritance.
## Passing Objects as Arguments (Collaboration)
A common pattern in Java is passing an object of one class into a method of another class. This allows the receiving method to call methods *on that passed object*. This is the essence of **dependency injection** and loose coupling.
```java
// Printer.java
public class Printer {
public void printDocument(Document doc) {
// Calling a method on the passed object
String content = doc.getContent();
System.out.println("Printing: " + content);
}
}
// Document.java
public class Document {
private String content;
public Document(String content) {
this.content = content;
}
public String getContent() {
return content;
}
}
// MainClass.java
public class MainClass {
public static void main(String[] args) {
Document myDoc = new Document("Annual Report 2024");
Printer officePrinter = new Printer();
// Passing the object to another class's method
officePrinter.printDocument(myDoc);
}
}
In this example, Printer does not need to know how Document stores its data; it only needs to know that Document has a getContent() method. This promotes polymorphism—you could pass any object that implements a Printable interface with a getContent() method Small thing, real impact. No workaround needed..
Calling Methods via Constructors and Initialization Blocks
Sometimes, you need to call a method from another class immediately during the creation of an object. This can be done inside a constructor or an instance initialization block.
// DatabaseConnector.java
public class DatabaseConnector {
public void connect() {
System.out.println("Establishing DB connection...");
}
public void initializeSchema() {
System.out.println("Initializing schema...");
}
}
// Application.out.Even so, db. Think about it: initializeSchema();
System. Still, db = connector;
// Calling methods on the dependency during initialization
this. java
public class Application {
private DatabaseConnector db;
// Constructor injection
public Application(DatabaseConnector connector) {
this.db.connect();
this.println("Application started.
// MainClass.java
public class MainClass {
public static void main(String[] args) {
DatabaseConnector connector = new DatabaseConnector();
// Constructor calls the methods internally
Application app = new Application(connector);
}
}
Caution: Calling overridable methods (non-final, non-private instance methods) from a constructor can be dangerous if the class is subclassed, as the subclass's override might run before the subclass constructor completes, potentially accessing uninitialized fields Which is the point..
Advanced Patterns: Method References and Functional Interfaces
Since Java 8, you can treat methods as first-class citizens using Method References (ClassName::methodName) and Functional Interfaces. This allows
Method references (ClassName::methodName) let you refer to an existing method or constructor without creating a new object that merely forwards the call. When a functional interface—an interface that declares exactly one abstract method—is used as the target type, a method reference becomes a compact way to supply the required behavior.
Functional interfaces and lambda expressions
A functional interface is any interface that contains a single abstract method, for example:
@FunctionalInterface
interface ContentProvider {
String get(); // the single abstract method
}
Because the interface has only one abstract method, a lambda expression can implement it directly:
ContentProvider provider = () -> "Dynamic content";
If the target type already defines a method with the same signature, a method reference can be used instead of a lambda:
class Document {
String getContent() { return "Annual Report 2024"; }
}
Document doc = new Document();
ContentProvider provider = doc::getContent; // method reference
Using method references with existing classes
- Static method reference –
String::valueOfrefers to the staticvalueOfmethod ofString. - Instance method reference –
printer::printrefers to an instance methodprintof thePrinterclass. - Constructor reference –
new Printer::newcreates aPrinterby calling its constructor.
These references can be passed to any API that expects a functional interface, eliminating the need for an anonymous inner class and making the code more readable Practical, not theoretical..
Example: pluggable printing behavior
Suppose we want a Printer that can use different strategies to obtain the text to print. Define a functional interface that captures the strategy:
@FunctionalInterface
interface TextProvider {
String supply(); // returns the text to be printed
}
The Printer class now accepts a TextProvider in its printDocument method:
public class Printer {
public void printDocument(TextProvider provider) {
System.out.println(provider.supply());
}
}
With this design we can plug in any implementation at call‑site:
Printer officePrinter = new Printer();
// static method reference
officePrinter.printDocument(String::valueOf);
// instance method reference
officePrinter.printDocument(doc::getContent);
// lambda expression
officePrinter.printDocument(() -> "Temporary report");
// constructor reference
officePrinter.printDocument(new Printer()::getContent);
Because the Printer class no longer knows the concrete way the text is produced, the system exhibits true behavioral flexibility without modifying the Printer implementation.
Built‑in functional interfaces
Since Java 8 the standard library supplies a rich hierarchy of functional interfaces in java.Think about it: util. function.
| Interface | Abstract method | Typical use |
|---|---|---|
Function<T,R> |
R apply(T t) |
Transform a value |
Consumer<T> |
void accept(T t) |
Perform an action, no result |
Supplier<T> |
T get() |
Provide |
The standard library’s java.So util. function package therefore extends far beyond the three shown in the table.
| Interface | Abstract method | Typical scenario |
|---|---|---|
Predicate<T> |
boolean test(T t) |
Filtering collections, validating input |
BiPredicate<T,U> |
boolean test(T t, U u) |
Two‑argument checks, such as range validation |
Function<T,R> |
R apply(T t) |
Mapping one type to another, e.g., converting a String to its length |
BiFunction<T,U,R> |
R apply(T t, U u) |
Combining two inputs into a result, like concatenating a prefix and a suffix |
UnaryOperator<T> |
T apply(T t) |
A specialized Function<T,R> where the result type matches the input type; handy for transformations that return the same category (e.g.Practically speaking, , String::toUpperCase) |
BinaryOperator<T> |
T apply(T t1, T t2) |
A specialized BiFunction<T,T,T> for operations that keep the same generic type (e. g. |
Illustrative snippets
// Predicate example – keep only the even numbers
List numbers = List.of(1, 2, 3, 4, 5);
numbers = numbers.stream().filter(n -> n % 2 == 0).collect(Collectors.toList());
// Function example – map a Person to their age
Person p = new Person("Alice", 30);
int age = Function.identity().apply(p); // identity function
int age2 = Person::getAge; // method reference to an instance method
// BiFunction example – create a pair from two strings
String combined = BiFunction
.apply("Hello", "World", s -> s + " " + t);
When to favor a method reference
- Simple, already‑named – If the target type already defines a method whose signature matches the functional interface, a method reference reads like natural language (
doc::getContent,printer::print). - Static utility –
String::valueOforMath::sqrtconvey intent instantly without extra ceremony. - Constructor calls –
new Printer::newreplaces() -> new Printer()and makes the intent of object creation explicit.
When a lambda remains preferable
- Complex logic – When the body requires multiple statements, branching, or captures additional variables, a lambda (
() -> { … }) preserves readability. - Unique behavior – If no existing method matches the signature, a lambda is the only viable option.
- In‑line implementation – Short, one‑liner actions such as
e -> System.out.println(e)keep the code compact without the overhead of defining a separate method.
Practical guidelines
- Prefer method references for clarity – They act as self‑documenting code; a future reader can instantly see which existing method is being invoked.
- Avoid over‑using them for obscure or hidden behavior – If the referenced method is far removed from the current class, the abstraction may obscure the actual work being performed.
- Keep lambdas focused – A lambda should ideally represent a single, well‑named operation; otherwise, extract it into a named method to preserve readability.
- Mind the capture scope – Lambdas can capture ambient variables, which may lead to unintended side effects. Method references, by contrast, never capture external state, reducing bugs.
Extending the pattern
The same principles apply when designing your own functional interfaces. By exposing a single abstract method, you enable callers to supply behavior through either a lambda or a method reference, thereby achieving the same degree of flexibility demonstrated by the built‑in types. To give you an idea, a MessageFormatter interface with a String format(Message m) method can be implemented via `
...a lambda such as m -> render(m) or a method reference such as MessageFormatter::format. Both approaches allow the interface’s implementors and clients to supply behavior without changing the interface itself, but they invite different implementation styles.
Once the distinction is clear, the choice becomes a matter of communication. Worth adding: a method reference reads like a pointer to existing behavior, while a lambda reads like a description of new behavior. The strongest designs make that difference obvious to the reader and avoid forcing either syntax into places where it does not fit naturally.
The real skill is knowing when to stop adding abstraction. Consider this: if the logic is simple and already has a name, use a method reference. That's why if it is complex, conditional, or captures state, use a lambda or extract it into a well-named method. This keeps the functional style expressive without turning every call site into a puzzle.
So, to summarize, method references and lambdas are complementary tools for implementing functional interfaces. Method references favor clarity and reuse when an existing method matches the intent, while lambdas offer flexibility for custom or context-dependent behavior. The best choice is the one that makes the code read most naturally, and the best designs keep that decision simple rather than leaving it open-ended Not complicated — just consistent..