*constructor is a special method used to initialize objects of a class
*constructors play an important role in object creation
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.
/ Java Program to demonstrate
// Default Constructor
import java.io.*;
// Driver class
class Geeks{
// Default Constructor
Geeks() {
System.out.println("Default constructor");
}
// Driver function
public static void main(String[] args)
{
Geeks hello = new Geeks();
}
}
Default Constructor VS Parameterized Constructor
Default Constructor
*A default constructor is a 0-argument constructor that contains a no-argument call to the super class constructor.
*Assigning default values to the newly created objects is the main responsibility of the default constructor.
*The compiler writes a default constructor in the code only if the program does not write any constructors in the class.
public class Student {
void display() {
int roll_no = 121;
String stu_name = "Suryavanshi";
System.out.println(roll_no + " " + stu_name);
}
public static void main(String args[]) {
Student s1 = new Student();
s1.display();
}
}
Parameterized Constructor
*The parameterized constructors are the constructors that have a specific number of arguments to be passed.
*The purpose of a parameterized constructor is to assign user-wanted specific values to the instance variables of different objects.
*A parameterized constructor is written explicitly by a programmer.
public class Student {
int roll_no;
String stu_name;
// Parameterized constructor
Student(int i, String n) {
roll_no = i;
stu_name = n;
}
void display() {
System.out.println(roll_no+" "+stu_name);
}
public static void main(String args[]) {
Student s1 = new Student(1,"Adithya");
Student s2 = new Student(2,"Jai");
s1.display();
s2.display();
}
}
Reffer :
https://www.geeksforgeeks.org/constructors-in-java/
https://www.tutorialspoint.com
To be discus ::A constructor in Java can not be abstract, final, static, or Synchronized. (Meaning புரியல)
Top comments (1)
Super bro