Constructor In Java
A constructor in Java is a special member that is called when an object is created. It
initializes the new object’s state. It is used to set default or user-defined values for the
object's attributes
• A constructor has the same name as the class.
• It does not have a return type, not even void.
• It can accept parameters to initialize object properties.
Types of Constructors in Java
1. Default Constructor
2. Parameterized Constructor
3. Copy Constructor
Default Constructor :
A default constructor has no parameters. It’s used to assign default values to an object.
If no constructor is explicitly defined, Java provides a default constructor.
Syntax:
MyClass() {
super();
}
Parameterised Constructor :
A constructor that has parameters is known as parameterized constructor. If we want
to initialize fields of the class with our own values, then use a parameterized
constructor.
Syntax :
class ClassName {
dataType variableName;
public ClassName(dataType parameter1, dataType parameter2, ...) {
[Link] = parameter1;
}
}
Copy Constructor :
Unlike other constructors copy constructor is passed with another object which copies
the data available from the passed object to the newly created object.
Syntax :
public class ClassName {
private int field1;
private String field2;
public ClassName(int f1, String f2) {
this.field1 = f1;
this.field2 = f2;
}
public ClassName(ClassName original) {
this.field1 = original.field1;
this.field2 = original.field2;
}
}