Skip to main content

Command Palette

Search for a command to run...

Java Programming Day 9

Updated
β€’5 min readβ€’View as Markdown
H

Hi! I'm a curious and self-driven programmer currently pursuing my BCA πŸŽ“ and diving deep into the world of Java β˜• from Day 1. I already have a foundation in programming, and now I'm expanding my skills one concept, one blog, and one project at a time. I’m learning Java through Bro Code’s YouTube tutorials, experimenting with code, and documenting everything I understand β€” from basic syntax to real-world applications β€” to help others who are just starting out too. I believe in learning in public, progress over perfection, and growing with community support. You’ll find beginner-friendly Java breakdowns, hands-on code snippets, and insights from my daily coding grind right here. πŸ’‘ Interests: Java, Web Dev, Frontend Experiments, AI-curiosity, Writing & Sharing Knowledge πŸ› οΈ Tools: Java β€’ HTML/CSS β€’ JavaScript β€’ Python (basics) β€’ SQL 🎯 Goal: To become a confident Full Stack Developer & AI Explorer πŸ“ Based in India | Blogging my dev journey

#JavaJourney #100DaysOfCode #CodeNewbie #LearnWithMe

🌞 Java Day 9: Constructors and Constructor Overloading – My Aha Moment!


πŸ‘‹ Introduction

Hey blog! Today was surprisingly fun and full of "aha" moments as I explored constructors and constructor overloading in Java. Initially, constructors seemed mysterious, but now I realize they’re fundamental for creating and initializing objects easily and flexibly.

In this post, I’ll share everything I learned with detailed examples, explanations, and insights that helped me really get it.


❓ What is a Constructor?

  • A constructor is a special method used to initialize objects in Java.

  • It has the same name as the class and no return type (not even void).

  • Automatically called when an object is created using the new keyword β€” you don’t have to call it explicitly.

  • It sets the initial state of the object (i.e., assigns values to its fields).


πŸ€” Why do we need constructors if we already have methods?

  • Methods perform actions after the object exists.

  • Constructors prepare the object itself when it’s created β€” they set initial values and ensure the object is ready to use.

Think of constructors like the β€œsetup” or β€œbuild” process for each new object.


πŸ“Œ Program 1: Basic Constructor – Student Class

javaCopyEditpublic class Student {
    String name;
    int age;
    double gpa;
    boolean isEnrolled;

    // Constructor to initialize the object
    Student(String name, int age, double gpa) {
        this.name = name;
        this.age = age;
        this.gpa = gpa;
        this.isEnrolled = true;  // Default enrollment status
    }

    void study() {
        System.out.println(name + " is currently studying πŸ“–");
    }
}

// Main.java
public class Main {
    public static void main(String[] args) {
        Student s1 = new Student("Himanshi", 18, 9.1);
        s1.study();
    }
}

Output:

csharpCopyEditHimanshi is currently studying πŸ“–

πŸ” Explanation:

  • When we create Student s1 = new Student("Himanshi", 18, 9.1); the constructor sets the name, age, GPA, and default enrollment status automatically.

  • We didn’t have to call any setters explicitly β€” the constructor did all the setup.

  • This makes object creation neat, clean, and less error-prone.


🀯 Then I met: Constructor Overloading!

What is Constructor Overloading?

  • Java allows multiple constructors in the same class as long as their parameter lists are different.

  • This means you can create objects in multiple ways, depending on how much info you have.


πŸ’» Program 2: Overloaded Constructors – UserProfile Class

javaCopyEditpublic class UserProfile {
    String username;
    String email;
    int age;

    // Default constructor
    UserProfile() {
        this.username = "Guest";
        this.email = "Not provided";
        this.age = 0;
    }

    // Constructor with username only
    UserProfile(String username) {
        this.username = username;
        this.email = "Not provided";
        this.age = 0;
    }

    // Constructor with username and email
    UserProfile(String username, String email) {
        this.username = username;
        this.email = email;
        this.age = 0;
    }

    // Constructor with username, email, and age
    UserProfile(String username, String email, int age) {
        this.username = username;
        this.email = email;
        this.age = age;
    }
}

// OverloadedConstructorDemo.java
public class OverloadedConstructorDemo {
    public static void main(String[] args) {
        UserProfile user1 = new UserProfile("Spongebob");
        System.out.println("User 1 β†’ " + user1.username + ", " + user1.email + ", Age: " + user1.age);

        UserProfile user2 = new UserProfile("Patrick", "patrick123@gmail.com");
        System.out.println("User 2 β†’ " + user2.username + ", " + user2.email + ", Age: " + user2.age);

        UserProfile user3 = new UserProfile("Sandy", "sandy123@gmail.com", 25);
        System.out.println("User 3 β†’ " + user3.username + ", " + user3.email + ", Age: " + user3.age);

        UserProfile user4 = new UserProfile();
        System.out.println("Guest User β†’ " + user4.username + ", " + user4.email + ", Age: " + user4.age);
    }
}

Output:

sqlCopyEditUser 1 β†’ Spongebob, Not provided, Age: 0
User 2 β†’ Patrick, patrick123@gmail.com, Age: 0
User 3 β†’ Sandy, sandy123@gmail.com, Age: 25
Guest User β†’ Guest, Not provided, Age: 0

πŸ” Explanation:

  • Multiple constructors provide flexibility β€” you don’t always need to provide all data at creation.

  • Default constructor creates a generic β€œGuest” user.

  • Other constructors allow partial or full initialization.

  • This is useful in real apps where user data might be incomplete or added over time.


⚑ Program 3: Quick Recap with Simple Prints

javaCopyEditUserProfile u1 = new UserProfile("Aditi");
UserProfile u2 = new UserProfile("Riya", "riya@gmail.com");
UserProfile u3 = new UserProfile("Megha", "megha@gmail.com", 20);
UserProfile u4 = new UserProfile();

System.out.println(u1.username + " | " + u1.email + " | " + u1.age);
System.out.println(u2.username + " | " + u2.email + " | " + u2.age);
System.out.println(u3.username + " | " + u3.email + " | " + u3.age);
System.out.println(u4.username + " | " + u4.email + " | " + u4.age);

Output:

nginxCopyEditAditi | Not provided | 0
Riya | riya@gmail.com | 0
Megha | megha@gmail.com | 20
Guest | Not provided | 0

πŸ‘€ Key Takeaways from Day 9:

  • Constructors automatically run when objects are created to initialize their state.

  • They don’t have return types, unlike regular methods.

  • Constructor overloading allows multiple ways to create objects depending on available data.

  • You can set default values, partial values, or complete values at creation time.

  • Constructors help enforce object consistency by ensuring important fields are set up early.


🧠 FAQs I Asked Myself:

QuestionAnswer
Can a class have multiple constructors?Yes, as long as their parameters differ.
What if I don’t write any constructor?Java gives a default no-arg constructor.
Are constructors inherited?No, constructors are not inherited.
Can constructors call each other?Yes, using this() inside constructors (next topic!).

🏁 Final Thoughts

Constructors are like the welcome gatekeeper of any Java object β€” they prepare the object before use. Overloading constructors is like giving multiple paths to enter, each tailored for different needs.

I’m excited to dive into constructor chaining next β€” understanding how constructors can call each other for even cleaner code.

Until then, happy coding and happy Java-ing! β˜•βœ¨