Sneha Burhade’s Post

Day 42 – Java 2026: Smart, Stable & Still the Future Topic: Constructor in Java What is a Constructor? A constructor is a special method in Java that is automatically executed when an object is created. It is mainly used to initialize object data. Simple definition: A constructor initializes the state of an object at the time of object creation. Rules for Creating a Constructor • Constructor name must be the same as the class name • Constructor does not have a return type (not even void) • Constructor is automatically called when the object is created • Can be overloaded • Cannot be static, final, or abstract • If no constructor is written, Java provides a default constructor Types of Constructors in Java Default Constructor No-Argument Constructor Parameterized Constructor Copy Constructor (User-defined) One-Line Explanation of Each Constructor 1. Default Constructor Automatically provided by JVM when no constructor is defined in the class. 2. No-Argument Constructor A constructor explicitly created by programmer that takes no parameters. 3. Parameterized Constructor A constructor that accepts parameters to initialize object values. 4. Copy Constructor A constructor that copies values from one object to another object. Small Example (All Types) class Student { String name; int age; // No-Argument Constructor Student() { name = "Unknown"; age = 0; } // Parameterized Constructor Student(String n, int a) { name = n; age = a; } // Copy Constructor Student(Student s) { name = s.name; age = s.age; } } public class Main { public static void main(String[] args) { Student s1 = new Student(); // No-arg Student s2 = new Student("Sneha", 22); // Parameterized Student s3 = new Student(s2); // Copy System.out.println(s1.name + " " + s1.age); System.out.println(s2.name + " " + s2.age); System.out.println(s3.name + " " + s3.age); } } Key Points • Constructor runs only once per object • Used for initialization • Supports overloading • Improves object creation control Key Takeaway: Constructor ensures every object starts with a valid and predictable state. #Java #Constructor #OOP #LearnJava #JavaDeveloper #Programming #100DaysOfCode

  • diagram

To view or add a comment, sign in

Explore content categories