Java Constructor
Java constructors are special methods used to initialize objects. A constructor is automatically called when an object of a class is created. It is mainly used to assign initial values to object attributes.
In this tutorial, you will learn about Java constructors, constructor syntax, types of constructors, default constructor, parameterized constructor, and examples.
What is a Constructor in Java?
A constructor in Java is a special block of code that has the same name as the class and does not have any return type. It is executed automatically when an object is created.
Constructors are used to initialize the state or properties of an object.
Java Constructor Syntax
class ClassName {
ClassName()
{
// constructor body
}
}
Example of Java Constructor
Let us take an example to understand how a constructor initializes an object in Java.
class Student {
String name;
Student()
{
name = "John";
}
public static void main(String[] args){
Student obj = new Student();
System.out.println(obj.name);
}
}
Types of Constructors in Java
Java provides mainly two types of constructors:
Default Constructor
A constructor without parameters is called a default constructor.
Parameterized Constructor
A constructor that accepts parameters to initialize object values is called a parameterized constructor.
Default Constructor in Java
A default constructor does not take any arguments. It assigns default values to the object properties.
class Car {
Car()
{
System.out.println("Car Created");
}
public static void main(String[] args)
{
Car c = new Car();
}
}
Parameterized Constructor in Java
A parameterized constructor accepts one or more values as parameters. It is used to initialize objects with specific values.
class Student {
String name;
Student(String n)
{
name = n;
}
public static void main(String[] args){
Student s = new Student("Alex");
System.out.println(s.name);
}
}
Advantages of Constructors in Java
- Constructors initialize objects automatically.
- They reduce repeated initialization code.
- They make object creation easier.
- They improve code readability.
- They help set initial object values.
Difference Between Constructor and Method
- Constructor has the same name as the class, while a method can have any name.
- Constructor does not have a return type, while methods can return values.
- Constructor is called automatically, while methods are called manually.
Conclusion
Java constructors are an important part of object-oriented programming. They are used to initialize objects and assign initial values when objects are created. Understanding constructors helps developers create efficient Java programs.