温馨提示×

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

小亿
96
2024-01-04 03:41:08
栏目: 编程语言

在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方法后,会在控制台输出"调用了其他类中的方法"。

0