Constructors and Initialization
Duration: 5 min
What are Constructors?
A constructor is a special method that is called when an object is created. It initializes the object's attributes with initial values. Every class has at least one constructor - if you don't define one, Java provides a default constructor.
Types of Constructors
• Default Constructor: Takes no parameters, initializes attributes to default values
• Parameterized Constructor: Takes parameters to initialize attributes with specific values
• Constructor Overloading: Multiple constructors with different parameters
public class Student {
private String name;
private int rollNumber;
private double gpa;
// Default constructor
public Student() {
this.name = "Unknown";
this.rollNumber = 0;
this.gpa = 0.0;
}
// Parameterized constructor
public Student(String name, int rollNumber) {
this.name = name;
this.rollNumber = rollNumber;
this.gpa = 0.0;
}
// Constructor with all parameters
public Student(String name, int rollNumber, double gpa) {
this.name = name;
this.rollNumber = rollNumber;
this.gpa = gpa;
}
public void displayInfo() {
System.out.println("Name: " + name + ", Roll: " + rollNumber + ", GPA: " + gpa);
}
}No output - this is a class definitionpublic class StudentDemo {
public static void main(String[] args) {
// Using default constructor
Student s1 = new Student();
s1.displayInfo();
// Using parameterized constructor
Student s2 = new Student("Alice", 101);
s2.displayInfo();
// Using constructor with all parameters
Student s3 = new Student("Bob", 102, 3.8);
s3.displayInfo();
}
}Name: Unknown, Roll: 0, GPA: 0.0
Name: Alice, Roll: 101, GPA: 0.0
Name: Bob, Roll: 102, GPA: 3.8The this Keyword
The 'this' keyword refers to the current object. It's used to:
• Distinguish between instance variables and parameters with the same name
• Call other constructors in the same class
• Return the current object
public class ThisExample {
private String name;
private int age;
// Constructor using 'this'
public ThisExample(String name, int age) {
this.name = name; // 'this.name' refers to instance variable
this.age = age; // 'this.age' refers to instance variable
}
public void display() {
System.out.println("Name: " + this.name + ", Age: " + this.age);
}
}No output - this is a class definition💡 Tip: Constructor overloading allows you to create objects in different ways. Choose the constructor that best fits your needs.
Learn more: https://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html
❓ What is the purpose of a constructor?
❓ What is a best practice when working with Constructors and Initialization?
💡 Tip: Pro Tip: Master Constructors and Initialization thoroughly. This foundation is crucial for writing professional Java code.