How can Java call methods from other classes?
In Java, to invoke methods from other classes, you first need to create an object of that class and then call the method through the object.
The sample code is as follows:
// 其他类
public class OtherClass {
public void otherMethod() {
System.out.println("调用了其他类中的方法");
}
}
// 主类
public class MainClass {
public static void main(String[] args) {
// 创建OtherClass对象
OtherClass other = new OtherClass();
// 调用OtherClass对象的方法
other.otherMethod();
}
}
In the example, a class named OtherClass is first defined, which includes a method called otherMethod. Then in the main class MainClass, an object of OtherClass named other is created, and the otherMethod method is called through the other object, achieving the invocation of methods in another class. After executing the main method of the main class, “Calling a method in another class” will be output to the console.