Below we have sorted and summarized based on JAVA's calling methods, and also tested the related calling code. Let's learn it below.
There are three main types of java methods:
One is a static method
This method is modified with static, and this method does not need to be bound to a specific object; the second is the common method without static modification; the third is the construction method, which is mainly used to initialize the class.
A static method can be called using a defined and instantiated object or directly using the class name.
An instance method must be called using a defined and instantiated object.
class A{ // Static method, you can directly call it using the class name and point the method name, such as A.sayHello() public static void saysHello(){ System.out.println("static method output successfully: Hello"); } // Instance method, you must create an instance of the class before you can call A a = new A(); a.sayWorld(); public void saysWorld(){ System.out.println("Instance method output successfully: World"); }} public class MyDemo { public static void main(String[] args) { A a = null; try{ a.sayHello();//Calling the static method}catch(NullPointerException e){ System.out.println("A null pointer exception occurred when calling the static method"); } try{ a.sayWorld();//Calling the instance method}catch(NullPointerException e){ System.out.println("A null pointer exception occurred when calling the instance method"); } }} Test output:
Static method output successfully: Hello
A null pointer exception occurred when calling the instance method
Java dynamically calls method code in class
Use Math.class.getDeclaredMethod("sin", Double.TYPE); to access the specified method, where "sin" means the name of the method to be accessed is sin, and Double.TYPE means the type of the entry parameter is double
import java.lang.reflect.Method; public class DongTai { public static void main(String[] args) { try { System.out.println("Call the static method sin() of the Math class"); Method sin = Math.class.getDeclaredMethod("sin", Double.TYPE); Double sin1 = (Double) sin.invoke(null, new Integer(1)); System.out.println("1's sine value is: " + sin1); System.out.println("Call the non-static method equals() that calls String class"); Method equals = String.class.getDeclaredMethod("equals", Object.class); Boolean mrsoft = (Boolean) equals.invoke(new String("Tomorrow Technology"), "Tomorrow Technology"); System.out.println("Is the string Tomorrow Technology: " + mrsoft); } catch (Exception e) { e.printStackTrace(); } } }The output result after running