How to instantiate an object in Java?
In Java, the keyword “new” can be used to instantiate an object. The specific steps are as follows:
- Firstly, it is necessary to define a class to represent the type of an object. Classes can have attributes and methods.
- “fresh”
- Create a new instance of the ClassName class and assign it to the objectName variable.
- name of the object
Below is an example demonstrating how to instantiate an object called Person:
public class Person {
String name;
int age;
public void sayHello() {
System.out.println("Hello, my name is " + name);
}
}
public class Main {
public static void main(String[] args) {
// 实例化一个Person对象
Person person = new Person();
person.name = "John";
person.age = 25;
// 调用对象的方法
person.sayHello();
}
}
In the example above, we first defined a class called Person with two properties, name and age, as well as a method called sayHello(). Then, in the main method, we used the new keyword to instantiate a Person object and assigned it to a variable called person. Next, we were able to access the object’s properties and call the object’s method. In this case, we set the name to “John”, the age to 25, and called the sayHello() method to print a greeting.