java call method from another class example

java call method from another class example

To call a method from another class in Java, simply create an instance of the class and use the point operator (.) to access the method. Here is an example of how to call a method from another class:

refer to‮al:‬utturi.com
public class Main {
  public static void main(String[] args) {
    // Creates an instance of the OtherClass class
    OutraClasse obj = new OutraClasse();

    // Calls the object method
    obj.mymethod();
  }
}

public class OutraClasse {
  public void mymethod() {
    System.out.println("This is the method of the OtherClass class");
  }
}

In this example, the 'Main' class has a 'main' method that is the entry point of the application. The method creates an instance of the 'OtherClass' class using the 'new' operator and stores the reference in an 'obj' variable. The method then calls the 'mymethod' method of the 'Other Class' class using the point operator (.) and the method is executed.

Note that to call a method from another class, you must have access to the class (that is, it must be in the same package or must be public) and the method must be public as well. Additionally, you must import the class if it is in a different package using the 'import' declaration.

Created Time:2017-11-03 00:14:47  Author:lautturi