Linux 拨号vps windows公众号手机端

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

lewis 8年前 (2017-05-04) 阅读数 7 #程序编程
文章标签 Java

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

版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门