what is constructor in java?
In Java, constructors play an important role in object creation. A constructor is a special block of code that is called when an object is created. Its main job is to initialize the object, to set up its internal state, or to assign default values to its attributes. This process happens automatically when we use the "new" keyword to create an object.
Characteristics of Constructors:
Same Name as the Class: A constructor has the same name as the class in which it is defined.
No Return Type: Constructors do not have any return type, not even void. The main purpose of a constructor is to initialize the object, not to return a value.
Automatically Called on Object Creation: When an object of a class is created, the constructor is called automatically to initialize the object’s attributes.
Used to Set Initial Values for Object Attributes: Constructors are primarily used to set the initial state or values of an object’s attributes when it is created.
class Constructor {
int rollno;
String name;
String qualification;
int age;
String bloodgroup;
Constructor(int rollno,String name,String qualification,int age,String bloodgroup){
this.rollno = rollno;
this.name = name;
this.qualification = qualification;
this.age = age;
this.bloodgroup=bloodgroup;
}
void GetEmployee(){
System.out.println("rollno:"+rollno);
System.out.println("name:"+name);
}
void GetBi0data(){
System.out.println("qualification:"+qualification);
System.out.println("age:"+age);
}
void GetDetail(){
System.out.println("bloodgroup:"+bloodgroup);
}
public static void main (String[] args){
Constructor Con = new Constructor(23213,"Rajan","bsc",20,"o+");
Con.GetEmployee();
Con.GetBi0data();
Con.GetDetail();
}
}
Output:
rollno:23213
name:Rajan
qualification:bsc
age:20
bloodgroup:o+
Top comments (0)