Low Orbit Flux Logo 2 F

Java How To Call A Method From Another Class

Calling a method from another class in Java is easy. We are going to show you how you can do this today.

Quick Answer - To call a method from another class first create an instance of the class. Then call the method using dot notation. For example:


OtherClass object1 = new OtherClass();
object1.doWorkMethod1();

Keep reading for more complete examples that include additional variations of this problem that you are likely to run into. We are going to cover static, public, protected, and private methods.

Call a public Method in Another Class in Java

This is just about the most basic example that we could come up with. It doesn’t really do anything but it illustrates how you would call a method in the simplest possible way.


class Data1{
    private String a  = "This is a line of text.";
    
    public String getA() {
        return this.a;
    }
}

public class Test1 {
    public static void main(String[] args) {    
        Data1 d1 = new Data1();
        String s1 = d1.getA();
        System.out.println(s1);
    }
}

Call a static Method in Another Class

Calling a static method from another class is actually a bit easier because you don’t even really need to create an instance of the class.


class Data1{
    static String a = "Some random string";

    static String getA() {
        return this.a;
    }
}

public class Test1 {
    public static void main(String[] args) {
        String s1 = Student.getA();
        System.out.println(s1);
    }
}

Call a private Method in Another Class

You can’t call a private method in another class. These methods are only accessible from within the class that they are defined in. The best you could do is to use or create another method in that class that calls or otherwise provides access to the private method.

Call a protected Method in Another Class

A protected method can only be called from a subclass. Notice that in the example here Test1 extends the class Data1. This allows us to call the protected method getA() from that class.


class Data1{    
    protected String a;
    
    protected String getA() {
        return this.a;
    }
}
public class Test1 extends Data1 {    
    public static void main(String[] args) {
        Data1 d1 = new Data1();
        String s1 = d1.getA();
        System.out.println(s1);
    }
}