How to call another class in Java?

To call another class in Java, create an instance of that class and call the desired method.

1. Calling an instance method

If the method you want to call is an instance method, then you need to create an instance of the class first and then call the method:

class ClassToCall {

  public void someMethod() {
    // does something…
  }
}

class CallerClass {

  public void callingMethod() {
    new ClassToCall().someMethod();
  }
}

2. Calling a static method

If the method you want to call is a static method, then you can call it directly:

class ClassToCall {

  public static void someMethod() {
    // does something…
  }
}

class CallerClass {

  public void callingMethod() {
    ClassToCall.someMethod();
  }
}