How to Call Method of Another Class in Java
Learning how to call method of another class in Java is one of the first real milestones on the path from writing single-file scripts to building structured applications. Java is designed around the idea that behavior lives inside classes, so almost nothing useful happens without one class reaching out to another. This guide walks through every practical way to make that call — from the everyday object instantiation approach to static calls, dependency passing, inheritance, interfaces, and even the rare reflection case — with working code you can paste into your IDE and run Took long enough..
Not the most exciting part, but easily the most useful.
Introduction: Why Classes Need to Talk to Each Other
A class in Java is a blueprint: it groups fields (data) and methods (behavior) into a single reusable unit. By itself, a blueprint does nothing. The moment you have a BankAccount class, an EmailService class, and a Main class, you need a way for one to invoke the logic defined in another That's the whole idea..
That mechanism is a method call, and the exact syntax depends on four things:
- Whether the target method is static or an instance method
- The access modifier on that method (
public,protected,private, or package-private) - Whether the two classes live in the same package or different packages
- Whether you already hold a reference to an object of that class
Once you understand those four variables, calling methods across classes stops being confusing and becomes almost mechanical.
The Foundation: Instance Methods and Object References
An instance method belongs to an object, not to the class itself. To call it, you must first create an object, then use the dot operator And it works..
public class Calculator {
public int add(int a, int b) {
return a + b;
}
}
public class Main {
public static void main(String[] args) {
Calculator calc = new Calculator(); // 1. add(5, 7); // 2. call the method with a dot
System.create the object
int result = calc.out.
The pattern is always the same three steps:
1. **Declare** a variable of the class type.
2. **Instantiate** the class with the `new` keyword (this invokes its constructor).
3. **Invoke** the method using `objectReference.methodName(arguments)`.
The dot operator is the heart of Java method invocation. `calc` is a *reference*, not the object itself; the JVM follows that reference to find the object on the heap and then dispatches the call to the correct method.
## Calling Static Methods Without Creating an Object
If a method is declared with the `static` keyword, it belongs to the **class** rather than any instance. You call it using the **class name**, and no object is required.
```java
public class MathUtils {
public static int square(int n) {
return n * n;
}
}
public class Main {
public static void main(String[] args) {
int value = MathUtils.Plus, square(6); // class name, not object name
System. out.
This is why you write `Math.Also, parseInt("42")` without ever creating a `Math` object. max(10, 20)` or `Integer.Static methods are ideal for **utility functions** that do not depend on object state.
A common beginner trap: Java *allows* you to call a static method through an object reference (`calc.square(6)`), but the compiler will warn you. Always prefer `ClassName.method()` for clarity.
## Calling Methods From Another Package
When classes live in different **packages**, two extra requirements appear: the target class and method must be `public`, and you must either **import** the class or use its **fully qualified name**.
```java
// file: com/myapp/utils/StringHelper.java
package com.myapp.utils;
public class StringHelper {
public static String reverse(String input) {
return new StringBuilder(input).reverse().toString();
}
}
// file: com/myapp/Main.java
package com.myapp;
import com.myapp.utils.StringHelper; // required import
public class Main {
public static void main(String[] args) {
String result = StringHelper.In practice, reverse("java");
System. out.
If the method is package-private (no modifier), it is invisible outside its own package, and your code will not compile.
## Access Modifiers: What You Are Actually Allowed to Call
Access control decides whether a cross-class call is legal at all.
| Modifier | Same class | Same package | Subclass | Anywhere |
|---|---|---|---|---|
| `public` | Yes | Yes | Yes | Yes |
| `protected` | Yes | Yes | Yes | No |
| *(default)* | Yes | Yes | No | No |
| `private` | Yes | No | No | No |
Real talk — this step gets skipped all the time.
The practical rule: **expose only what callers need**. Keep helper methods `private`, and make the entry points `public`.
## Passing Objects as Parameters (Dependency Injection)
Instead of creating a new object inside every class, you can **receive** the object you need. This is the manual form of *dependency injection*, and it is the backbone of testable, loosely coupled Java code.
```java
public class NotificationService {
public void send(String message) {
System.out.println("Sending: " + message);
}
}
public class OrderProcessor {
private final NotificationService notifier;
public OrderProcessor(NotificationService notifier) {
this.notifier = notifier; // store the dependency
}
public void processOrder(String orderId) {
System.out.println("Processing " + orderId);
notifier.
public class Main {
public static void main(String[] args) {
NotificationService notifier = new NotificationService();
OrderProcessor processor = new OrderProcessor(notifier);
processor.processOrder("A-1024");
}
}
Because OrderProcessor depends on an injected service rather than a hard-coded new NotificationService(), you can swap in a fake implementation during unit tests. This is exactly the principle frameworks like Spring formalize And that's really what it comes down to..
Method Chaining: Calling Across Classes in One Line
When a method returns an object, you can chain another call directly onto it.
public class Request {
private String url = "";
public Request setUrl(String url) {
this.url = url;
return this; // return this enables chaining
}
public String build() {
return "GET " + url;
}
}
// Usage
String result = new Request().setUrl("/api/users").build();
Returning this is the technique behind the fluent interface style used in builders, streams, and query APIs Surprisingly effective..
Inheritance: Using super to Call a Parent
Inheritance: Using super to Call a Parent
When a class extends another class, it inherits the fields and methods of its parent. On top of that, often you need to initialize the parent’s state or invoke a parent implementation of a method. The super keyword is the gateway to those capabilities.
1. Invoking a Superclass Constructor
A subclass constructor must confirm that the superclass is properly constructed before its own body runs. This is achieved by placing a call to super(..) as the first statement in the subclass constructor.
class Animal {
protected String name;
public Animal(String name) {
this.Practically speaking, name = name; // initialise Animal’s state
System. out.
class Dog extends Animal {
private String breed;
public Dog(String name, String breed) {
super(name); // mandatory first line
this.breed = breed; // then initialise Dog‑specific state
System.out.
If the superclass does not expose a no‑argument constructor, the explicit `super(..)` call is required; otherwise the compiler will insert a default call that may be illegal.
#### 2. Overriding Methods and Calling the Parent Implementation
A subclass may **override** a method to provide specialised behaviour. Within the override, you can still reuse the parent’s logic by invoking it via `super.methodName(args)`.
```java
class Animal {
public void speak() {
System.out.println(name + " makes a sound");
}
}
class Cat extends Animal {
@Override
public void speak() {
System.out.print("The cat says "); // custom greeting
super.
In this example the `Cat` class adds a prefix before delegating to the generic `speak` implementation defined in `Animal`. This pattern preserves the **contract** of the parent while allowing extension.
#### 3. Accessing Superclass Fields
If a field in the superclass is declared `protected` (or package‑private when the subclass resides in the same package), the subclass can reference it directly:
```java
class Bird {
protected String wingShape;
}
class Eagle extends Bird {
public void describeWings() {
System.out.println("Wings are " + wingShape);
}
}
When a field is private, the subclass cannot see it, and any attempt to override a method that accesses a private superclass field will not compile.
4. The super Keyword in Static Context
super is instance‑specific; it cannot be used inside static methods because there is no concrete instance to resolve the superclass reference. If you need static behaviour that mirrors a parent, consider using a static helper method or redesigning the hierarchy The details matter here. Nothing fancy..
5. Multiple Inheritance via Interfaces
Java’s single‑class inheritance model means a class can extend only one direct superclass. Also, to reuse behaviour without deep inheritance, implement multiple interfaces that each declare methods. The class then provides concrete implementations, and super can be used inside those methods just as with a regular subclass Easy to understand, harder to ignore..
interface Flyable {
void fly();
}
interface Swimmable {
void swim();
}
class Duck implements Flyable, Swimmable {
public void fly() {
System.out.println("Duck flaps wings and lifts off");
}
public void swim() {
System.out.println("Duck paddles on the water");
}
}
Here the class implements two interfaces, each defining a method that the class supplies its own body for; super is not involved because the methods originate from the interface contract rather than a class hierarchy.
6. Best Practices
- **Always
super.methodName() when you want to extend rather than replace parent behaviour, so you keep the original contract intact Simple, but easy to overlook..
-
Avoid deep inheritance chains. Prefer composition or interfaces over multi‑level hierarchies; they are easier to test and less brittle when requirements change.
-
Do not call
superin a constructor of a class that does not extend anything. Every class implicitly extendsObject, sosuper()is always valid, but an explicit call is only meaningful when you are deliberately chaining to a specific parent constructor It's one of those things that adds up. That alone is useful.. -
Keep field access intentional. Exposing state through
protectedfields couples subclasses to the parent’s internal representation. Favourprotectedaccessor methods so the superclass can evolve without breaking descendants. -
Remember that
superis resolved at compile time. Unlike overridden methods invoked through a reference (which are dispatched dynamically to the runtime type), asupercall is bound statically to the parent implementation. Use it when you specifically want to bypass a subclass override That's the part that actually makes a difference. Worth knowing.. -
Watch for accidental hiding. If a subclass declares a field or static method with the same name as one in the parent, it hides rather than overrides it.
super.fieldandsuper.staticMethod()let you reach the hidden member explicitly, which is often a sign the naming collision should be reconsidered.
7. A Complete Example
Bringing the pieces together, the following program demonstrates constructor chaining, method overriding with delegation, and access to a protected field:
class Vehicle {
protected String label;
public Vehicle(String label) {
this.label = label;
System.out.
public void start() {
System.out.println(label + " is starting");
}
}
class Motorcycle extends Vehicle {
public Motorcycle(String label) {
super(label); // chain to parent constructor
}
@Override
public void start() {
System.print("Revving engine... out.");
super.
public class Demo {
public static void main(String[] args) {
Motorcycle bike = new Motorcycle("Ninja");
bike.start();
}
}
Output:
Vehicle created: Ninja
Revving engine... Ninja is starting
The Motorcycle constructor forwards its argument to Vehicle via super(label), and the overridden start() method prints a custom message before delegating to the parent implementation Which is the point..
Conclusion
The super keyword is a small but powerful part of Java’s inheritance toolkit. It gives you three distinct capabilities: chaining to a parent constructor, delegating to a parent method while still adding your own behaviour, and reaching members that a subclass has hidden or that are exposed through protected access. Used well, it lets subclasses extend rather than discard the behaviour they inherit, preserving the contracts that make a class hierarchy predictable And that's really what it comes down to..
The key ideas to carry forward are simple. Because of that, use super. method() when you want to augment a parent method instead of replacing it outright. Keep in mind that super is instance‑bound and therefore illegal in static contexts, and that Java’s single‑inheritance model is best complemented by interfaces when you need to combine behaviours from several sources. Use super(...) as the first statement of a constructor to initialise inherited state. Combined with a preference for shallow hierarchies and composition over deep inheritance, a disciplined use of super produces code that is both flexible and easy to reason about Practical, not theoretical..