Home  >  Article  >  Java  >  How to call classes in java

How to call classes in java

下次还敢
下次还敢Original
2024-05-01 19:46:09874browse

Calling class methods in Java: 1. Create an instance of the class; 2. Use the dot operator of the instance method; 3. Call the static method directly; 4. Pass the necessary parameters.

How to call classes in java

Methods called by classes in Java

Calling methods of classes in Java is very simple, just follow the following Steps:

  1. Create an instance of the class: Use the new keyword to create an instance of the class, for example:
<code class="java">Person person = new Person();</code>
  1. Calling instance methods: Use the dot operator (.`) to call instance methods of a class, for example:
<code class="java">person.setName("John Doe");</code>
  1. Calling static methods: If the method is declared static, you can call it directly using the class name, for example:
<code class="java">Person.printStaticMessage();</code>
  1. Pass parameters: If the method requires parameters, you can put them in parentheses Pass them, for example:
<code class="java">person.greet("Hello!");</code>

Example:

Here is an example showing how to call the class:

<code class="java">class Person {
    private String name;

    public void setName(String name) {
        this.name = name;
    }

    public void greet(String message) {
        System.out.println(message + ", " + name + "!");
    }

    public static void printStaticMessage() {
        System.out.println("This is a static message.");
    }
}

public class Main {
    public static void main(String[] args) {
        Person person = new Person();
        person.setName("John Doe");
        person.greet("Hello");
        Person.printStaticMessage();
    }
}</code>

Output:

<code>Hello, John Doe!
This is a static message.</code>

The above is the detailed content of How to call classes 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