乐闻世界logo
搜索文章和话题

How are objects created in Java?

2月7日 00:13

In Java, objects are created using the new keyword. First, we define a class, which serves as a blueprint for creating objects. When using the new keyword to instantiate a class, the Java Virtual Machine (JVM) allocates heap memory for the object and invokes the constructor to initialize it.

For example, consider a class named Person:

java
public class Person { String name; int age; public Person(String name, int age) { this.name = name; this.age = age; } }

We can create an instance of the Person class as follows:

java
Person person = new Person("John Doe", 30);

In this case, the new Person("John Doe", 30) expression first allocates heap memory for the Person object, then invokes the constructor of the Person class, passing "John Doe" and 30 as arguments to initialize the object.

标签:Java