Constructor in Java 🚀
By Bhau Automation • Java OOPs Tutorial for Beginners
🎯 What You Will Learn
- What is a constructor in Java?
- Purpose of constructor
- Types of constructors
- Java constructor examples
- Java interview questions on constructors
💡 Constructors are one of the most important OOPs concepts in Java and are widely used in real-world applications.
📌 What is a Constructor in Java?
A constructor in Java is a special method used to initialize objects. It is automatically called when an object is created.
Important points about constructors:
- Constructor name must be same as class name
- Constructors do not have return type
- Called automatically during object creation
- Used to initialize variables
⚙️ Purpose of Constructor
Constructors are mainly used for:
- Initializing object data
- Reducing repetitive code
- Assigning default values
- Improving code readability
🛠️ Syntax of Constructor
class Student {
Student() {
System.out.println("Constructor Called");
}
}
💻 Default Constructor Example
class Employee {
Employee() {
System.out.println("Default Constructor");
}
public static void main(String[] args) {
Employee e = new Employee();
}
}
💻 Parameterized Constructor Example
class Student {
int id;
String name;
Student(int i, String n) {
id = i;
name = n;
}
void display() {
System.out.println(id + " " + name);
}
public static void main(String[] args) {
Student s1 = new Student(101, "Rahul");
s1.display();
}
}
📚 Types of Constructors in Java
- Default Constructor
- Parameterized Constructor
- Copy Constructor (custom implementation)
🔥 Rules of Constructors
- Constructor cannot be static
- Constructor cannot be abstract
- Constructor can be overloaded
- Constructor executes only once per object creation
🌍 Real-World Use Cases
- Banking applications
- Student management systems
- Automation frameworks
- Spring Boot applications
❓ Common Interview Questions
Q: Can constructor return a value?
A: No, constructors do not have return type.
Q: Can we overload constructors in Java?
A: Yes, constructor overloading is allowed in Java.
Q: What happens if constructor is not created?
A: Java automatically provides a default constructor.
🎥 Watch Complete Video Tutorial
👉 Watch Constructor in Java Tutorial
🎓 Key Takeaways
- Constructors initialize objects in Java
- Constructors are automatically called
- Parameterized constructors help assign custom values
- Constructor overloading improves flexibility
- Important Java interview topic
⚡ Pro Tip: Practice constructor programs daily to build strong understanding of object creation and OOPs concepts.
🚀 Created with ❤️ by Bhau Automation