What is Constructor?
A constructor is a special method in a class that is used to initialize objects when they are created. It has the same name as the class and does not have any return type, not even void. The constructor is automatically called whenever an object of the class is created, so there is no need to call it manually. Its main purpose is to assign initial values to the instance variables and set up the object properly. Constructors help make the code cleaner and ensure that every object starts with the required data.
Why Constructor used?
A constructor is used to initialize objects when they are created. It helps assign initial values to variables so the object starts in a proper state. Without a constructor, you would need to set values manually every time after creating an object. Constructors also make the code cleaner and more organized. They ensure that required data is set at the time of object creation itself.
Example 1: Default Constructor
class Student {
String name;
Student() {
name = "Unknown";
}
public static void main(String[] args) {
Student s = new Student();
System.out.println(s.name);
}
}
Output: Unknown
Example 2: Parameterized Constructor
class Student {
String name;
Student(String n) {
name = n;
}
public static void main(String[] args) {
Student s = new Student("Hello");
System.out.println(s.name);
}
}
Output: Hello
Example 3: Multiple Values
class Car {
String brand;
int price;
Car(String b, int p) {
brand = b;
price = p;
}
public static void main(String[] args) {
Car c = new Car("BMW", 5000000);
System.out.println(c.brand + " " + c.price);
}
}
Output: BMW 5000000
Top comments (0)