A constructor in Java is a special type of method used to initialize objects. It is called when an object of a class is created. Constructors have the same name as the class and do not have a return type.
void
.class Dog {
Dog() {
System.out.println("A new dog object is created!");
}
}
public class Main {
public static void main(String[] args) {
= new Dog(); // Calls the default constructor
Dog myDog }
}
class Dog {
String name;
int age;
Dog(String name, int age) {
this.name = name;
this.age = age;
}
void display() {
System.out.println("Dog's Name: " + name + ", Age: " + age);
}
}
public class Main {
public static void main(String[] args) {
= new Dog("Buddy", 3); // Calls the parameterized constructor
Dog myDog .display();
myDog}
}
Just like methods, constructors can also be overloaded by having multiple constructors with different parameters in a class.
class Dog {
String name;
int age;
// Default constructor
Dog() {
this.name = "Unknown";
this.age = 0;
}
// Parameterized constructor
Dog(String name, int age) {
this.name = name;
this.age = age;
}
void display() {
System.out.println("Dog's Name: " + name + ", Age: " + age);
}
}
public class Main {
public static void main(String[] args) {
= new Dog(); // Calls the default constructor
Dog dog1 = new Dog("Buddy", 3); // Calls the parameterized constructor
Dog dog2
.display();
dog1.display();
dog2}
}
Constructor chaining refers to the process of calling one constructor
from another constructor within the same class or from a superclass
constructor. This can be done using the this()
or
super()
keywords.
this()
:class Dog {
String name;
int age;
Dog() {
this("Unknown", 0); // Calls the parameterized constructor
}
Dog(String name, int age) {
this.name = name;
this.age = age;
}
void display() {
System.out.println("Dog's Name: " + name + ", Age: " + age);
}
}
public class Main {
public static void main(String[] args) {
= new Dog(); // Calls the default constructor
Dog dog1 = new Dog("Buddy", 3); // Calls the parameterized constructor
Dog dog2
.display();
dog1.display();
dog2}
}
super()
to Call Superclass Constructorssuper()
keyword is used to call the constructor of
the superclass. It must be the first statement in the subclass
constructor.class Animal {
Animal() {
System.out.println("Animal is created");
}
}
class Dog extends Animal {
Dog() {
super(); // Calls the superclass constructor
System.out.println("Dog is created");
}
}
public class Main {
public static void main(String[] args) {
= new Dog();
Dog myDog }
}
Constructors are essential in Java for initializing objects and providing flexibility in object creation. Understanding constructors and their various types helps in writing more efficient and maintainable code.