Here is a simple example that creates an object, which results in the class constructor being called:
MyClass myClassObj = new MyClass();
This example results in a new MyClass object being created, and the no-arg constructor of MyClass to be called.
- A Java class constructor initializes instances (objects) of that class.
- Typically, the constructor initializes the fields of the object that need initialization.
- Java constructors can also take parameters, so fields can be initialized in the object at creation time.
public class MyClass {
public MyClass() {
}
}
The constructor is this part:
public MyClass() {
}
Constructor overloading example :
public class MyClass {
private int number = 0;
public MyClass() {
}
public MyClass(int theNumber) {
this.number = theNumber;
}