How to invoke a method from another class using Java?

To call a method of another class in Java, you can follow these steps:

  1. Creating an instance of the target class: To begin, you need to create an instance of the target class. This can be done by using the constructor of the target class, for example: TargetClass target = new TargetClass();
  2. Call a method through an object: Use the created object to access the methods of the target class by using the dot operator (.). For example, target.methodName();

Here is a complete example:

public class TargetClass {
    public void methodName() {
        // 在此处编写方法的具体实现
        System.out.println("调用了目标类的方法");
    }
}

public class MainClass {
    public static void main(String[] args) {
        // 创建目标类的对象
        TargetClass target = new TargetClass();

        // 调用目标类的方法
        target.methodName();
    }
}

In the code above, TargetClass is the target class that contains a method named methodName. MainClass is the main class where an object named target of TargetClass is created in the main method, and the methodName method from TargetClass is called using target.methodName().

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds