Java Constructors
What is a Constructor?
- A constructor is a special method used to initialize objects.
- It has the same name as the class and no return type.
Syntax:
class ClassName {
ClassName() {
// constructor code
}
}
Example:
class Car {
String brand;
// Constructor
Car() {
brand = "Tesla";
}
void display() {
System.out.println(brand);
}
}
public class Main {
public static void main(String[] args) {
Car myCar = new Car(); // Constructor is called automatically
myCar.display();
}
}
Output:
Tesla
Types of Constructors
Type | Meaning |
---|---|
Default Constructor | No parameters |
Parameterized Constructor | Accepts parameters |
Example of Parameterized Constructor:
class Student {
String name;
int rollNo;
// Parameterized Constructor
Student(String n, int r) {
name = n;
rollNo = r;
}
void display() {
System.out.println(name + " (" + rollNo + ")");
}
}
public class Main {
public static void main(String[] args) {
Student s1 = new Student("Alice", 101);
s1.display();
Student s2 = new Student("Bob", 102);
s2.display();
}
}
Output:
Alice (101)
Bob (102)
Difference between Method and Constructor
Feature | Method | Constructor |
---|---|---|
Purpose | Perform actions | Initialize objects |
Name | Any valid name | Same as class name |
Return type | Required (even void) | No return type |
Called by | Explicitly | Automatically when object is created |