Home > Java > javaTutorial > body text

How to call classes in java

下次还敢
Release: 2024-05-01 19:46:09
Original
949 people have browsed it

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>
Copy after login
  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>
Copy after login
  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>
Copy after login
  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>
Copy after login

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>
Copy after login

Output:

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

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template