要调用另一个类的方法,首先需要实例化该类的对象,然后通过该对象调用方法。
例如,有一个名为"AnotherClass"的类,其中有一个名为"anotherMethod"的方法。
public class AnotherClass { public void anotherMethod() { System.out.println("调用了AnotherClass类中的anotherMethod方法"); } }
在另一个类中,可以通过以下步骤调用"AnotherClass"类的"anotherMethod"方法:
-
导入"AnotherClass"类所在的包(如果在同一个包中则无需导入)。
-
实例化"AnotherClass"类的对象。
AnotherClass object = new AnotherClass();
- 通过对象调用"anotherMethod"方法。
object.anotherMethod();
完整的示例代码如下:
import 包名.AnotherClass; public class Main { public static void main(String[] args) { AnotherClass object = new AnotherClass(); object.anotherMethod(); } }