How to call a Method from Another Class in Java

Calling a method from another class in Java
Fig 1: Dot notation can be used to call a method from another class in Java.

In Java, a method is a function associated with a class or object. As with other functions, methods allow developers to package code in a way that allows them to be re-used. 

Although methods in Java are associated with a class, they can still be called from another class. This allows developers much more flexibility to tap into the benefits of methods; if we couldn’t call a method from outside the class, then its’ functionality would inherently be limited to that class. 

In general, calling a method from another class is easy, but how we do it changes slightly depending on the situation. In this article, we’ll cover the following cases:

  1. Calling a static method from another class
  2. Calling a public method from another class
  3. Calling a protected method from another class
  4. Calling a private method from another class

Let’s start with a brief review of classes and methods in Java. This will help us to better understand the problem and its’ solutions.

A Review of Java Classes and Methods

In Java, a class is a template for creating objects. Classes are an important part of Java’s embrace of object-oriented programming (OOP). They define the structure and behavior of objects, allowing us to create instances (objects) that have certain attributes (data members or fields) and can also perform actions (methods or functions).

Here are some key characteristics of classes in Java:

1. Attributes: Classes can have attributes which are also known as fields or member variables. Attributes represent the data associated with objects of that class. Fields define the state of an object.

2. Methods: Classes contain methods, which are functions associated with the class. Methods define the behavior of objects created from the class. Each method of a class facilitates a unique behavior. They encapsulate the functionality that objects may perform.

3. Constructors: Classes often include constructors, which are special methods used to initialize objects when they are created. Constructors have the same name as the class, and can take parameters to set initial values for the object’s fields.

4. Access Modifiers: Java classes can use access modifiers (e.g., `public`, `private`, `protected`, or package-private) to control the visibility and accessibility of their fields and methods.

5. Inheritance: One class (the subclass or derived class) may inherit the attributes and methods of another class (the superclass or base class). Inheritance promotes code reuse and the creation of hierarchical class structures.

6. EncapsulationFields are often declared as private or protected and accessed through getter and setter methods. This helps in controlling access to and manipulation of the class’s data.

As an example, let’s create a simple Java class called `Rectangle` that represents rectangles. It will include a constructor to initialize the dimensions (length and width), and methods to calculate the area and perimeter of a rectangle. 

We’ll then instantiate two `Rectangle` objects and call the methods to perform calculations:

public class Rectangle { 
    // Attributes 
    private double length; 
    private double width; 
    // Constructor to initialize a rectangle 
    public Rectangle(double length, double width) { 
        this.length = length; 
        this.width = width; 
    } 
    // Method to calculate the area 
    public double calculateArea() { 
        return length * width; 
    } 
    // Method to calculate the perimeter 
    public double calculatePerimeter() { 
        return 2 * (length + width); 
    } 
    public static void main(String[] args) { 
        // Create two Rectangle objects 
        Rectangle rectangle1 = new Rectangle(5.0, 3.0); 
        Rectangle rectangle2 = new Rectangle(7.0, 4.0); 
        System.out.println("Rectangle 1:"); 
        System.out.println("Area: " + rectangle1.calculateArea()); 
        System.out.println("Perimeter: " + rectangle1.calculatePerimeter()); 
        System.out.println("\nRectangle 2:"); 
        System.out.println("Area: " + rectangle2.calculateArea()); 
        System.out.println("Perimeter: " + rectangle2.calculatePerimeter()); 
    } 
} 

Output:

Rectangle 1:
Area: 15.0
Perimeter: 16.0
Rectangle 2:
Area: 28.0
Perimeter: 22.0

In this example, we’ve created a `Rectangle` class with fields for length and width, a constructor to initialize these fields when creating a `Rectangle` object, and two methods (`calculateArea` and `calculatePerimeter`) to perform calculations on the rectangle’s dimensions.

In the `main` method, we create two `Rectangle` objects (`rectangle1` and `rectangle2`), set their dimensions, and then call the methods to calculate and display their areas and perimeters.

Calling a Static Method from Another Class

In Java, a static method is a method that belongs to a class rather than an instance of the class. In other words, a static method is associated with the class itself, not with any specific object or instance. Static methods are defined using the static keyword in the method declaration.

We can call a static method of one class from another class by using the class name followed by the dot (`.`) operator:

ClassName.staticMethodName(arguments);

We don’t need to create an instance of the class to call a static method. 

The following code illustrates how to call a static method from one class in another class:

Suppose we have a class called `MathUtils` with a static method `add`:

public class MathUtils { 
    public static int add(int num1, int num2) { 
        return num1 + num2; 
    } 
} 

We can call this static method from another class, such as `MainApp`, like this:

public class MainApp { 
    public static void main(String[] args) { 
        int result = MathUtils.add(5, 3); // Calling the static method from MathUtils 
        System.out.println("The sum is: " + result); 
    } 
} 

In this example, `MathUtils.add(5, 3)` is used to call the `add` static method of the `MathUtils` class from within the `MainApp` class. You don’t need to create an instance of `MathUtils` to use the static method; you can directly access it through the class name.

Calling a public method from another class

In Java, a public method is a method declared with the `public` access modifier. Public methods are accessible from any class, whether it’s in the same package or a different package, as long as the class itself is accessible.

They are part of the class’s interface, and they can be called by instances of the class or by other classes. A public method is also considered to be an instance method, because it is called on an instance using a dot operator.

In order to call the public method, we will need to first create an instance of a class containing the method. Then we will be able to call the method using a similar technique to the previous example (of calling a static method).

To clarify, we can call the public method of one class from another class using these steps:

  1. Create an instance (object) of the class that contains the public method.
  2. Use the instance to call the public method using the dot (`.`) operator.

The following example shows this:

// Define a class with a public method

class MyClass { 
    public void myMethod() { 
        System.out.println("This is a public method."); 
    } 
} 
// Define another class that calls the public method 
public class AnotherClass { 
    public static void main(String[] args) { 
        // Create an instance of MyClass 
        MyClass myObj = new MyClass(); 
        // Call the public method using the instance 
        myObj.myMethod(); 
    } 
} 

Output:

This is a public method.

In this example, `myMethod` is a public method in the `MyClass` class. In the `AnotherClass` class, we created an instance of `MyClass` using `MyClass myObj = new MyClass();`, and then we called the public method `myMethod` using the `myObj` instance with `myObj.myMethod();`. 

Calling a Protected Method from Another Class

In Java, a protected method is a method that is declared with the `protected` access modifier. Protected methods are accessible from within the same package, and can also be accessed by subclasses, even if the subclass is in a different package.

As with calling a public method from another class, in order to call a protected method of another class, we will first need to create an instance of the class containing it.

To call a protected method of one class from another class, we can follow these steps:

  1. Make sure that the class containing the protected method is accessible from the class where you want to call from. This typically means that both classes should be in the same package, or the class calling the method should be a subclass of the class containing the protected method.
  2. Create an instance of the class that contains the protected method.
  3. Use the instance to call the protected method using the dot (`.`) operator.

Here’s an example:

package mypackage; // The same package 
// Define a class with a protected method 
public class ParentClass  
    protected void protectedMethod() { 
        System.out.println("This is a protected method."); 
    } 
} 
// Define another class in the same package 
public class AnotherClass { 
    public static void main(String[] args) { 
        // Create an instance of ParentClass 
        ParentClass parentObj = new ParentClass(); 
        // Call the protected method using the instance 
        parentObj.protectedMethod(); 
    } 
} 

Output:

This is a protected method.

In the above program, both `ParentClass` and `AnotherClass` are in the same package (`mypackage`). The `protectedMethod` in `ParentClass` is accessible to `AnotherClass` because they are in the same package. We create an instance of the parent class using `ParentClass parentObj = new ParentClass();`, and then we call the protected method `protectedMethod` using the `parentObj` instance with `parentObj.protectedMethod();`.

Calling a Private Method from Another Class

In Java, a private method is a method declared with the `private` access modifier. Private methods are only accessible within the class in which they are defined. As a result, they cannot be accessed or called from outside the class, including other classes or subclasses. 

However, this doesn’t mean that a private method can’t be called! It just can’t be called directly. To get around this, we can create a non-private method that calls the private method from within the same class.

Here’s an example program illustrates this concept:

// Define a class with a private method 
class MyClass { 
    private void privateMethod() { 
        System.out.println("This is a private method."); 
    } 
    public void callPrivateMethod() { 
        // Call the private method from within the same class 
        privateMethod(); 
    } 
} 
// Define another class that attempts to call the private method (this will result in an error from the java compiler) 
public class AnotherClass { 
    public static void main(String[] args) { 
        MyClass myObj = new MyClass(); 
        // Attempting to call the private method (this will result in a compilation error) 
        // myObj.privateMethod(); 
        myObj.callPrivateMethod(); 
    } 
} 

Output:

This is a private method.

In the above example, `privateMethod` is a private method within the `MyClass` class. If we attempt to call `myObj.privateMethod();` from the `AnotherClass` class, it will result in an error because private methods cannot be accessed from outside the class in which they are defined.

In order to access privateMethod(), we have created a public method within MyClass called callPrivateMethod(). This method calls privateMethod() for us, enabling us to access it from a different class.

Calling a Method from Another Class in Java

In this article, we’ve seen several different ways to call a method from a different class in Java.

These examples correspond to the types of different methods, including static, public, protected, and private methods. Java provides an easy way to call these methods by using dot notation. In the case of public and protected methods, we will need to instantiate an object of the class. Private methods can be called from outside their class, but they require a non-private calling method that lives inside their class.

Hopefully this tutorial was helpful to you and the core concepts it covered has helped you to grow as a Java developer.

Check out our other Java tutorials and full course on the Java programming language!