What is the method for instantiating objects in Java?
In Java, the method of instantiating an object is using the new keyword followed by the object’s constructor. This process can be broken down into the following steps:
- To declare an object reference variable: first, you need to declare an object reference variable to store the instantiated object.
- Allocate memory: create an instance of an object using the new keyword and assign memory space for the object.
- Invoking the constructor: By calling the object’s constructor, the object is initialized. The constructor is a special method that has the same name as the class, does not have a return type, and is automatically called when an object is instantiated.
Here is a simple sample code that demonstrates how to instantiate an object.
public class MyClass {
private int value;
public MyClass(int value) {
this.value = value;
}
public int getValue() {
return value;
}
public static void main(String[] args) {
// 实例化对象
MyClass obj = new MyClass(10);
// 调用对象的方法
int value = obj.getValue();
System.out.println("Value: " + value);
}
}
In the example above, a MyClass object is instantiated with new MyClass(10) and the parameter 10 is passed to the constructor for initialization. Then, the getValue() method of the object is called through obj to retrieve and print the object’s value.