Java Constructors
A constructor in Java is a special method used to initialize objects.
It is called automatically when an object is created.
It has the same name as the class and has no return type.
Constructor Java में एक विशेष method होता है जो objects को initialize करता है।
यह method object बनते ही अपने आप call होता है।
इसका नाम class के जैसा होता है और इसका कोई return type नहीं होता।
Example 1: Default Constructor
public class Student {
Student() {
System.out.println("Default constructor called");
}
public static void main(String[] args) {
Student s1 = new Student();
}
}
Default constructor called
Default constructor runs when object is created.
Object बनते ही default constructor चल जाता है।
Example 2: Parameterized Constructor
public class Student {
String name;
Student(String n) {
name = n;
}
void display() {
System.out.println("Name: " + name);
}
public static void main(String[] args) {
Student s1 = new Student("Aryan");
s1.display();
}
}
Name: Aryan
Constructor takes input and assigns value to variable.
Constructor input लेता है और variable को value देता है।
Example 3: Constructor Overloading
public class Student {
String name;
int age;
Student() {
name = "Unknown";
age = 0;
}
Student(String n, int a) {
name = n;
age = a;
}
void display() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
public static void main(String[] args) {
Student s1 = new Student();
Student s2 = new Student("Abhishek", 25);
s1.display();
s2.display();
}
}
Name: Unknown Age: 0 Name: Abhishek Age: 25
Overloading allows multiple constructors with different parameters.
Overloading से एक class में अलग-अलग parameters वाले constructor बना सकते हैं।