Constructors are a fundamental concept in Java and play a crucial role in object-oriented programming (OOP). They help in initializing objects and ensuring that an instance of a class starts with the right values. In this article, we will dive deep into what constructors are, their different types, and how they are used in Java. We will also discuss their benefits and real-world applications to give you a solid understanding of constructors.
Contents:
- What are Constructors in Java?
- Example of Java Constructor
- Types of Constructors in Java
- Default Constructor in Java
- Parameterized Constructor in Java
- Copy Constructor in Java
- Constructor Overloading in Java
- Constructor Vs Method in Java
- Rules and Properties of Constructors
- FAQs on Constructors in Java
What are Constructors in Java?
A constructor in Java is a special method that gets called automatically when an object of a class is created. It is primarily used to initialize objects and set initial values for instance variables. The key characteristics of a constructor are:
- It has the same name as the class.
- It does not have a return type, not even void.
- Runs automatically when an object is created using new.
Example of Java Constructor
Below is the implementation of Java Constructors:
public class SanfoundryCourse { String courseName; // Constructor SanfoundryCourse() { courseName = "Java Programming"; } public void display() { System.out.println("Course: " + courseName); } public static void main(String[] args) { SanfoundryCourse obj = new SanfoundryCourse(); obj.display(); } }
Output:
Course: Java ProgrammingExplanation:
- The constructor SanfoundryCourse() initializes the variable courseName with “Java Programming”.
- When an object is created, the constructor is automatically called.
- The display() method prints the course name.
Types of Constructors in Java
In Java, constructors are mainly of three types:
- Default Constructor (No-Argument Constructor)
- Parameterized Constructor
- Copy Constructor (Not Built-in, but Can Be Created Manually)
Default Constructor in Java
A default constructor is a constructor that does not take any parameters and initializes an object with default values. If no constructor is defined in a class, Java automatically provides a default constructor.
Example:
public class SanfoundryQuiz { String topic; int totalQuestions; // Default constructor SanfoundryQuiz() { topic = "Java"; totalQuestions = 50; } public void display() { System.out.println("Sanfoundry MCQ Topic: " + topic); System.out.println("Total Questions: " + totalQuestions); } public static void main(String[] args) { SanfoundryQuiz quiz = new SanfoundryQuiz(); quiz.display(); } }
Output:
Sanfoundry MCQ Topic: Java Total Questions: 50
Explanation:
- The SanfoundryQuiz class has a default constructor that initializes the topic as “Java” and totalQuestions as 50.
- When an object of the class is created (quiz), it automatically gets these default values.
- The display() method prints the topic and number of questions.
- This ensures that every quiz object has default values, making it ready for use without manual input.
Parameterized Constructor in Java
A parameterized constructor is a constructor that takes arguments to initialize an object with specific values. Unlike a default constructor, it allows passing data at the time of object creation, making object initialization more flexible.
Example:
// Parameterized Constructor Example public class SanfoundryMCQ { String topic; // Parameterized Constructor public SanfoundryMCQ(String topic) { this.topic = topic; } public void showTopic() { System.out.println("Sanfoundry MCQ on: " + topic); } public static void main(String[] args) { SanfoundryMCQ mcq = new SanfoundryMCQ("Java"); mcq.showTopic(); } }
Output:
Sanfoundry MCQ on: JavaExplanation:
- This program demonstrates a parameterized constructor in Java.
- The class SanfoundryMCQ has an instance variable topic, which is initialized using a constructor that takes a parameter.
- When an object of the class is created using new SanfoundryMCQ(“Java”), the constructor assigns “Java” to the topic variable.
- The showTopic() method then prints the assigned topic. This approach ensures that an object is always initialized with a value at the time of creation.
Copy Constructor in Java
Java does not provide a built-in copy constructor, but you can create one manually. A copy constructor in Java is a special constructor used to create a new object by copying the values of an existing object.
Example:
public class SanfoundryMCQ { String topic; // Parameterized Constructor public SanfoundryMCQ(String topic) { this.topic = topic; } // Copy Constructor public SanfoundryMCQ(SanfoundryMCQ mcq) { this.topic = mcq.topic; } public void showTopic() { System.out.println("Sanfoundry MCQ on: " + topic); } public static void main(String[] args) { // Original object SanfoundryMCQ original = new SanfoundryMCQ("Java"); // Copying the object SanfoundryMCQ copy = new SanfoundryMCQ(original); original.showTopic(); copy.showTopic(); } }
Output:
Sanfoundry MCQ on: Java Sanfoundry MCQ on: Java
Explanation:
- This program demonstrates a copy constructor by creating a duplicate MCQ topic object.
- The copy constructor initializes the new object with the same topic as the original.
- Both objects display the same MCQ topic, proving that the copy was successful.
Constructor Overloading in Java
Constructor overloading in Java means having multiple constructors in the same class, each with a different number or type of parameters. This allows objects to be created in different ways, depending on the given input.
Example:
public class SanfoundryQuiz { String topic; int questions; // Default Constructor public SanfoundryQuiz() { this.topic = "General Knowledge"; this.questions = 10; } // Parameterized Constructor public SanfoundryQuiz(String topic) { this.topic = topic; this.questions = 20; } // Parameterized Constructor with two parameters public SanfoundryQuiz(String topic, int questions) { this.topic = topic; this.questions = questions; } public void display() { System.out.println("Sanfoundry Quiz on: " + topic); System.out.println("Total Questions: " + questions); } public static void main(String[] args) { SanfoundryQuiz quiz1 = new SanfoundryQuiz(); SanfoundryQuiz quiz2 = new SanfoundryQuiz("Java"); SanfoundryQuiz quiz3 = new SanfoundryQuiz("C Programming", 30); quiz1.display(); quiz2.display(); quiz3.display(); } }
Output:
Sanfoundry Quiz on: General Knowledge Total Questions: 10 Sanfoundry Quiz on: Java Total Questions: 20 Sanfoundry Quiz on: C Programming Total Questions: 30
Explanation:
- The SanfoundryQuiz class in Java demonstrates constructor overloading, where multiple constructors allow different ways to initialize an object.
- The default constructor sets the quiz topic to “General Knowledge” and the number of questions to 10.
- The first parameterized constructor takes a custom topic as input and sets the number of questions to 20.
- The second parameterized constructor allows full customization by accepting both the topic and the number of questions.
- In the main() method, three objects are created using these constructors, and their details are displayed using the display() method.
- This program highlights the importance of constructors in object initialization and the use of constructor overloading to provide flexibility in creating objects.
Constructor Vs Method in Java
The table below highlights the key differences between a constructor and a method in Java:
| Feature | Constructor | Method |
|---|---|---|
| Purpose | Used to initialize an object | Used to perform operations or return a value |
| Name | Must have the same name as the class | Can have any name |
| Return Type | No return type (not even void) |
Must have a return type (void or any other type) |
| Invocation | Called automatically when an object is created | Explicitly called using an object |
| Overloading | Can be overloaded (multiple constructors with different parameters) | Can be overloaded and overridden |
| Inheritance | Not inherited by subclasses | Inherited and can be overridden in subclasses |
| Default Availability | If no constructor is defined, Java provides a default constructor | No default methods are provided by Java |
Rules and Properties of Constructors
Rules of Constructors:
- Same Name as Class – Must have the same name as the class.
- No Return Type – Constructors do not have a return type.
- Auto Invocation – Called automatically when an object is created.
- No Inheritance – Not inherited, but can be called using super().
- Overloading Allowed – Multiple constructors with different parameters are allowed.
- No static, final, or abstract – Cannot have these modifiers.
- Can Have Access Modifiers – public, private, protected, or default.
Properties of Constructors:
- Default Constructor – If no constructor is defined, Java provides a default constructor that initializes instance variables with default values.
- Parameterized Constructor – Allows setting custom values at the time of object creation.
- Constructor Chaining – One constructor can call another within the same class using this(), or in a superclass using super().
- Used for Object Initialization – Primarily initializes instance variables when an object is created.
- Cannot be Called Explicitly Like Methods – It is automatically called when an object is instantiated.
FAQs on Constructors in Java
1. What is a constructor in Java?
A constructor is a special method in Java that is used to initialize an object when it is created. It has the same name as the class and does not have a return type.
2. Why do we need constructors in Java?
Constructors help in setting up the initial state of an object. Without a constructor, you would have to manually assign values to an object’s attributes after creating it.
3. How is a constructor different from a method?
A constructor is called automatically when an object is created, while a method needs to be explicitly called. Also, constructors do not have a return type, whereas methods must specify one.
4. What are the types of constructors in Java?
There are three types of constructors in Java:
- Default Constructor (no arguments, initializes with default values)
- Parameterized Constructor (accepts arguments to set initial values)
- Copy Constructor (creates a new object by copying values from another object)
5. What happens if a class doesn’t have a constructor?
If no constructor is defined, Java automatically provides a default constructor that initializes objects with default values (e.g., null for objects, 0 for numbers, false for booleans).
6. Can a constructor be static?
No, constructors cannot be static because they belong to instances of a class, not the class itself. However, you can use a static method (like a factory method) to return an instance of a class.
Key Points to Remember
Here is the list of key points we need to remember about the “Constructors in Java”.
- A constructor runs automatically when an object is created and helps initialize it with default or custom values.
- It must have the same name as the class and cannot have a return type.
- Java has three types of constructors: Default, Parameterized, and Copy Constructor.
- Constructor overloading allows multiple constructors with different parameters in the same class.
- Constructors are not inherited, cannot be explicitly called like methods, but support constructor chaining using
this()orsuper(). - Constructors cannot be
static,final, orabstract, and if none is defined, Java provides a default constructor automatically.
Continue learning Java from basics to advanced topics in our complete Java Tutorial.
Practice what you’ve learned with topic-wise questions on our Java MCQs.