java如何调用其他类中的方法

avatar
作者
筋斗云
阅读量:0

在Java中,要调用其他类中的方法,需要先创建该类的对象,然后通过对象调用方法。

示例代码如下:

// 其他类 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();     } } 

在示例中,首先定义了一个名为OtherClass的类,其中包含了一个名为otherMethod的方法。然后在主类MainClass中,先创建了OtherClass的对象other,然后通过other对象调用了otherMethod方法,实现了对其他类中方法的调用。执行主类的main方法后,会在控制台输出"调用了其他类中的方法"。

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!