Home >Web Front-end >JS Tutorial >In Java, the main function of the new keyword is to instantiate an object

In Java, the main function of the new keyword is to instantiate an object

PHPz
PHPzOriginal
2024-02-18 21:49:11598browse

In Java, the main function of the new keyword is to instantiate an object

The new operator in Java is used to create an instance object of a class. It creates and initializes objects by calling the constructor method of the class.

In Java, when you need to use the methods and properties of a class, you must first create an object of the class. Use the new operator to allocate a memory space for an object in memory and call the constructor method of the class to initialize the object.

The following is a specific code example that demonstrates how to use the new operator to create an instance object of a class:

// 定义一个Person类
class Person {
    String name;
    
    // 构造方法,用于初始化对象
    Person(String n) {
        name = n;
    }
    
    // 方法,用于输出姓名
    void sayHello() {
        System.out.println("Hello, my name is " + name);
    }
}

// 在主方法中使用new操作符创建Person类的实例对象
public class Main {
    public static void main(String[] args) {
        // 使用new操作符创建一个Person类的实例对象p1,并调用构造方法进行初始化
        Person p1 = new Person("Alice");
        // 调用对象的方法
        p1.sayHello();  // 输出:Hello, my name is Alice
        
        // 使用new操作符创建另一个Person类的实例对象p2,并调用构造方法进行初始化
        Person p2 = new Person("Bob");
        // 调用对象的方法
        p2.sayHello();  // 输出:Hello, my name is Bob
    }
}

In the above code, we define a Person class, which contains a Constructor and a sayHello method. Use the new operator to create two instance objects p1 and p2 of the Person class in the main method, and call the object's method to output the corresponding results.

In short, the new operator in Java plays a very important role in the instantiation process of a class. It allocates memory space for the object and calls the constructor method for initialization, so that we can use the class in the program. Properties and methods.

The above is the detailed content of In Java, the main function of the new keyword is to instantiate an object. 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