How to create an object using a constructor method in Java?
In Java, we can use constructor methods to create objects. Constructors are special methods that must have the same name as the class and do not have a return type.
The following are the steps to create an object using a constructor method:
- Define a class and define a constructor method. The constructor method can have parameters, or it can have no parameters.
public class MyClass {
private int num;
// 无参数构造方法
public MyClass() {
num = 0;
}
// 带参数的构造方法
public MyClass(int n) {
num = n;
}
}
- fresh
- fresh
- fresh
MyClass obj1 = new MyClass(); // 调用无参数构造方法创建对象
MyClass obj2 = new MyClass(10); // 调用带参数的构造方法创建对象
- You can access an object’s properties or call an object’s methods using the object’s name.
int n = obj2.getNum(); // 调用对象的方法
System.out.println(n); // 打印对象的属性
Important notes:
- If a constructor is not defined in a class, Java will automatically provide a default constructor with no parameters.
- If a class has a constructor with parameters defined, but does not have a constructor without parameters, then the constructor with parameters must be used when creating an object.
- A class can have multiple constructors as long as they differ in the number or type of parameters.
I hope this can help you!