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

2008
2023/12/28 3:41:08
栏目: 编程语言
开发者测试专用服务器限时活动,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方法后,会在控制台输出"调用了其他类中的方法"。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: Dapr与Java框架如何集成