What is the Constructor in Java and What Are Its Types?
A constructor is a special method that is automatically called when an object is created. It has the same name as the class and no return type.
1. Default Constructor
class Student {
String name;
int age;
Student() {
name = "Unknown";
age = 0;
}
void display() {
System.out.println("Name: " + name + ", Age: " + age);
}
}
2. Parameterized Constructor
class Employee {
int empId;
String empName;
Employee(int id, String name) {
empId = id;
empName = name;
}
void show() {
System.out.println("ID: " + empId + ", Name: " + empName);
}
}
3. Constructor Overloading
class Rectangle {
double length, width;
Rectangle() {
length = 1;
width = 1;
}
Rectangle(double side) {
length = width = side;
}
Rectangle(double l, double w) {
length = l;
width = w;
}
double area() {
return length * width;
}
}
Master Java constructors with Online Learner and ace your coding interviews!
0
likes
Your Feedback
Help us improve by sharing your thoughts
Online Learner helps developers master programming, database concepts, interview preparation, and real-world implementation through structured learning paths.
Quick Links
© 2023 - 2026 OnlineLearner.in | All Rights Reserved.
