What is Constructor:
*It is a block of code that is used to initialize an object.
*It runs automatically when we create an object; the constructor of that class will be invoked immediately.
Why is a constructor needed:
- When an object is created, memory is allocated for it. Constructor helps in assigning initial values to the variables of that object at the time of creation.
Characteristics of a Constructor:
- Constructor name must be the same as the class name
- It does not have a return type (not even void)
- It invoked automatically and mainly used of object initialization
- It can be overloaded(multiple constructors in a class)
Example:
class Person {
String name;
int age;
// This is a constructor
Person(String name, int age) {
this.name = name;
this.age = age;
}
}
// Using the constructor:
Person john = new Person("John", 25);
When you write new Person("John", 25), Java calls the constructor and sets up the object with those values.
Types of Constructors:
- Default Constructor
- No Arguments Constructor
- Parameterized Constructor
1.1 What is a Default Constructor:
*When we don't provide any constructor, compiler will provide one, and that will be in the class file. It is used to provide the default values to the object, like 0, null, etc depending on the type
class Dog {
String name;
// Java automatically creates this if you don't write any constructor:
// public Dog() { }
}
Dog myDog = new Dog(); // Uses default constructor
2.1 What is a No Arguments Constructor:
- Arguments will not be there, and it will allow us to write logic when object is created. This is not similar to Default constructor
3.1 What is a Parameterized Constructor:
*A constructor that takes parameters to initialize the object with specific values.
class Dog {
String name;
int age;
// Parameterized constructor
Dog(String name, int age) {
this.name = name;
this.age = age;
}
}
Dog myDog = new Dog("Buddy", 3); // Passes values during creation
What is a This Keyword:
this is a reference to the current object in a method or constructor
- The most common use of this keyword is to eliminate the confusion between class attributes and parameters with the same name.
class Student {
String name; // This is a field
int age; // This is a field
public Student(String name, int age) {
this.name = name; // this.name = field, name = parameter
this.age = age; // this.age = field, age = parameter
}
}
Top comments (1)
Great overview of Constructors and why is needed. Great job!