JOOPs Through Java
Challenge roadmap
0/30 Days Completed 0 Learning Days

Day 17 of 30 · Week 3 — OOPS Fundamentals

Constructors and their types

1 Learn

A constructor sets up a new object. It has the same name as the class and no return type.

If you write no constructor, Java provides a default no-argument constructor. A parameterized constructor takes values to fill the fields.

A class can have several constructors with different parameters (constructor overloading).

Want more detail? Open the full lesson

2 See the Code

Java
class Student {
    String name;
    int year;

    Student() {
        name = "Unknown";
        year = 1;
    }

    Student(String n, int y) {
        name = n;
        year = y;
    }
}

public class Main {
    public static void main(String[] args) {
        Student s1 = new Student();
        Student s2 = new Student("Ananya", 2);
        System.out.println(s1.name + " " + s1.year);
        System.out.println(s2.name + " " + s2.year);
    }
}
  • Student() is a no-argument constructor with default values.
  • Student(String n, int y) is a parameterized constructor.
  • Java picks the constructor that matches the arguments given to new.

Output

Unknown 1
Ananya 2

3 Practice

  • Give your Car class a constructor Car(String brand, int speed) and create a car with it.

Try it in your own Java setup or write it in the Practice Notebook.

4 Quick Check

  1. 1. A constructor's return type is...

  2. 2. When is Java's default constructor provided?

Step 5

Answer and check the Quick Check above to unlock this.