0% found this document useful (0 votes)
7 views2 pages

Constructor in Java

A constructor in Java is a special member used to initialize an object's state upon creation, sharing the same name as the class and lacking a return type. There are three types of constructors: Default Constructor (no parameters), Parameterized Constructor (with parameters), and Copy Constructor (copies data from another object). Each type serves a specific purpose in setting default or user-defined values for an object's attributes.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views2 pages

Constructor in Java

A constructor in Java is a special member used to initialize an object's state upon creation, sharing the same name as the class and lacking a return type. There are three types of constructors: Default Constructor (no parameters), Parameterized Constructor (with parameters), and Copy Constructor (copies data from another object). Each type serves a specific purpose in setting default or user-defined values for an object's attributes.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

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;
}
}

You might also like