Arrays and Strings · Introduction to Java Programming

Constructors

Watch lectures

Constructors

1. What Is a Constructor? (beginner)

Constructor = special method that runs once at new to init object. Same name as class, NO return type (not even void!). Like house-warming: sets furniture on move-in!

2. Three Kinds (exam list + code!)

class Student {
    String name; int marks;
    Student() { name = "Unknown"; marks = 0; }              // 1. no-arg (default-ish!)
    Student(String n) { name = n; marks = 50; }             // 2. parameterized!
    Student(String n, int m) { name = n; marks = m; }       // 2b. overloaded!
    Student(Student s) { name = s.name; marks = s.marks; }  // 3. copy!
}
Student a = new Student();             // Unknown,0
Student b = new Student("Asha");       // Asha,50
Student c = new Student("Ravi", 87);   // Ravi,87
Student d = new Student(c);            // copy of c!

3. Rules (exam traps!)

  • NO return type: void Student() is a METHOD (not constructor — new ignores it!).
  • If YOU write none → Java gives free default (Student() zeroing). If you write ANY → free one GONE! (new Student() then fails!).
  • Constructors chain: this(...) calls sibling (must be FIRST line!). super(...) calls parent (Module 3!).
Student(String n) { this(n, 50); } // delegate! (clean overloading!)

4. Constructor vs Method (exam table!)

Constructor Method
Name = class any
Return none (not void!) void/type
Call once via new many via .
Job init work

5. Exam Points

  • Three kinds + program — 7 marks, very frequent.
  • Default-gone trap + void trap — 5 marks, favourite traps.
Free AppAndroid App

Coursify Android App

Generate AI courses, take quick quizzes between classes, and master complex engineering concepts on the go.

← All Introduction to Java Programming modules