Home >Java >javaTutorial >How to call class method in Java

How to call class method in Java

(*-*)浩
(*-*)浩Original
2019-05-05 13:58:3142446browse

The steps for Java to call a class method: first create a new class, and instantiate the called class in the calling class; then access it through the instantiated object; finally create a new class and add the class that needs to be called The method is set to static. After adding static, it can be called directly using the class name, in the format of "class name. method name (parameter list)".

How to call class method in Java

This article will introduce two situations of how to call methods of a class. If you want to know how to call the private method of a class.

Recommended course: Java Tutorial.

If the method in another class is private, it cannot be called directly. If it is of other types, it depends on the situation. If it is static, it can be called directly using the class name. If If it is non-static, it needs to be called using an instance of another class (that is, an object generated by that class).

Method 1. Create a new class. Then the called class is instantiated first in the calling class, and then accessed through the instantiated object. For example:

class Method{
    void add(){
        System.out.print("加法");
    }
}
public class Test{
    public static void main(String[] args){
        Method m=new Method();
        m.add();
    }
}

Method 2. Create a new class and set the method that needs to be called in the class as static. After adding static, you can call it directly with the class name. . Then directly access it through the

class name in the calling class. The calling format is: class name. method name (parameter list). For example:

class Method{
    static void add(){
        System.out.print("加法");
    }
}
public class Test{
    public static void main(String[] args){
        Method.add();
    }
}

The above is the detailed content of How to call class method in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn