How to invoke a function in Java?

In Java, functions can be called using the following methods:

  1. Calling a function directly: If the function is defined in the same class, you can call the function by using its name followed by the parameter list. For example:
public class MyClass {
    public void myFunction() {
        // 函数体
    }

    public static void main(String[] args) {
        MyClass myObject = new MyClass();
        myObject.myFunction(); // 调用myFunction函数
    }
}
  1. To call a function using an object: If the function is defined in another class, you need to create an object of that class and then use the object name followed by the function name and parameter list to call the function. For example:
public class MyOtherClass {
    public void myFunction() {
        // 函数体
    }
}

public class MyClass {
    public static void main(String[] args) {
        MyOtherClass myOtherObject = new MyOtherClass();
        myOtherObject.myFunction(); // 调用MyOtherClass类中的myFunction函数
    }
}
  1. To call a static function using the class name, you can simply use the class name followed by the function name and parameter list. For example:
public class MyOtherClass {
    public static void myStaticFunction() {
        // 函数体
    }
}

public class MyClass {
    public static void main(String[] args) {
        MyOtherClass.myStaticFunction(); // 调用MyOtherClass类中的静态函数
    }
}

It is important to note that when calling a function, the correct parameter list needs to be passed, with the parameters’ types and order matching the function’s definition. If the function returns a value, you can assign the return value to a variable or use it directly.

bannerAds