25
AprConstructors in Java: Types of Constructors with Examples
Java Programming For Beginners Free Course
Java Constructor: An Overview
Java Constructors are a special type of method that can help create an object and assign values to its instance variables upon its initialization. When learning the fundamentals of Java for beginners, understanding constructors is essential to utilizing this powerful programming language. So without further ado, let’s explore how Java utilizes constructors!
What is Constructor in Java?
Constructors in Java are special methods that allow the developer to create objects with specific parameters from classes. Polymorphism in Java Constructors has no return values, and they usually have the same name as the class. Initializing object member variables in constructors is not required but is advised for quick object setup.
They accept arguments to customize object behavior and allow the passing of initial data during instance formation. essential for effective software development in Java and other languages using Object-Oriented Programming.
Read More - Top 50 Java Programming Interview Questions
Need of Constructors in Java
- Java constructors and methods are similar, but there are some important distinctions.
- Constructors cannot have a return type and must have the same name as the class.
- They don't require manual calling because they are automatically called when an object is created.
- For initializing objects with default or initial states, constructors are crucial.
- They give us the ability to set particular values for object properties, guaranteeing that they don't rely on primitive default values.
- Additionally, constructors provide information about class dependencies.
- You may learn what dependencies a class needs for proper usage by looking at its constructor.
Example of constructor program in Java Compiler
public Employee() {
System.out.println("Employee Constructor");
}
public Employee Employee() {
System.out.println("Employee Method");
return new Employee();
}
The "Employee Constructor" text is printed whenever an instance of the "Employee" class is created in the first code block. By accident, the second block tries to define a method with the same name, but it isn't recognized as a constructor and instead returns a new "Employee" object while writing "Employee Method."
Types of constructor in Java
There are three types of constructors in Java, which are
- Default constructor in Java
- No arguments constructor in Java
- Parameterized constructor in Java
1.) Default Constructor in Java
- Default Constructors in Java are powerful tools for initializing fields in a class and object in Java.
- They are normally declared without any arguments, allowing the compiler to automatically create the constructor when an instance of the class is created.
- Default Constructors are particularly useful for setting default values, such as 0 and null where appropriate.
- Additionally, Default Constructors enable developers to allow for custom initialization code for optional parameter values, allowing them to set up objects with more specific settings that may be required by the user or program.
- Default Constructors are invaluable components of object-oriented programming and can help reduce development time and complexity.
Default Constructor in Java: Example
public class MyClass {
int myInt;
String myString;
// Default constructor
public MyClass() {
myInt = 0;
myString = "default";
}
public void display() {
System.out.println("myInt = " + myInt);
System.out.println("myString = " + myString);
}
public static void main(String[] args) {
MyClass obj = new MyClass();
obj.display();
}
}
The default constructor of this Java class, "MyClass," initializes "myInt" to 0 and "myString" to "default." The values of these variables can likewise be printed using the "display" method. The "main" method creates an instance of "MyClass," initializes it with the constructor, and then calls the "display" method to output the contents of its member variables.
Output
myInt = 0
myString = default
2.) No argument constructor in Java
- In Java, no argument constructors allow objects to be initialized with no data passed into them.
- A no-argument constructor is usually used when no information is needed to initialize the object.
- However, this type of constructor can create potential issues if certain conditions must be met before setting up an object.
- For example, an invariant may need to be set right away or a reference may need to be provided for the object to behave as expected.
- If a no-argument constructor is being utilized and these conditions are not met, there can sometimes be issues in other parts of the code.
- It is for this reason that Java developers often opt for more controlled methods of constructing objects via alternative ways such as overloaded constructors or factory methods instead of no-argument constructors.
No argument constructor in Java: Example
public class Person {
private String name;
private int age;
// Default constructor
public Person() {
this.name = "John Doe";
this.age = 30;
}
// Method to print a greeting message
public void sayHello() {
System.out.println("Hello, my name is " + this.name + " and I am " + this.age + " years old.");
}
// Main method to test the Person class
public static void main(String[] args) {
// Create an instance of the Person class
Person john = new Person();
// Call the sayHello method to print the greeting message
john.sayHello();
}
}
The "name" and "age" private member variables in this Java class, "Person," are initialized to "John Doe" & 30, respectively, by default in the constructor. Additionally, it provides a "sayHello" method that uses these settings to print a welcome message. When you will execute this code in the Java Online Compiler.
Output
Hello, my name is John Doe and I am 30 years old.
3.) Parameterized constructor in Java
- Parameterized constructors in Java allow developers to provide more flexibility when constructing objects.
- These constructors accept arguments that can be used for initializing the object's state.
- Parameterized constructors can be overloaded, allowing more than one version with different parameter lists to be called for various use cases.
- This is especially helpful for classes that represent complex objects that need to be initialized from different sets of information.
- The parameterized constructor also allows subclasses to call the superclass constructor and provide the necessary information required to create an instance of the subclass, making it easy to create a hierarchy of objects within programs.
- Parameterized constructors are a key concept laying at the foundation of object-oriented programming in Java and are incredibly useful when it comes to efficiently creating and organizing many types of data.
Parameterized constructor in Java: Example
class Person {
private String name;
private int age;
// Constructor to initialize name and age
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Method to print person's information
public void printInfo() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
}
public class Main {
public static void main(String[] args) {
// Create instances of Person class
Person person1 = new Person("John Doe", 30);
Person person2 = new Person("Jane Doe", 25);
// Print information of each person
person1.printInfo();
person2.printInfo();
}
}
The "name" and "age" fields of the "Person" class are set using a parameterized constructor defined in this Java code. It generates two "Person" objects in the "Main" class with different values—"John Doe" and 30 for person1 and "Jane Doe" and 25 for person2—and uses the "printInfo" function to print out their respective information.
Output
Name: John Doe
Age: 30
Name: Jane Doe
Age: 25
Read More - Java Developer Salary
Private Constructor in Java
- A private constructor in Java is a special type of constructor that is only accessible to the class that is defining it.
- This type of constructor was created to provide developers with more control over how objects are instantiated within their program.
- By using private constructors, a developer can ensure that their objects are always created in a predetermined manner, as private constructors cannot be called from outside the class.
- Furthermore, private constructors can help prevent duplicate objects from being created, preventing potential bugs and errors from arising.
- Private constructors offer a powerful tool for Java developers looking for better control over their code and object instantiation.
Private Constructor in Java: Example
class MyClass {
private static MyClass instance;
// Private constructor to prevent instantiation from outside
private MyClass() {
// private constructor
}
// Static method to get the singleton instance of MyClass
public static MyClass getInstance() {
if (instance == null) {
instance = new MyClass();
}
return instance;
}
// Method to display a message
public void showMessage() {
System.out.println("Hello, World!");
}
}
public class Main {
public static void main(String[] args) {
// Get the singleton instance of MyClass
MyClass myInstance = MyClass.getInstance();
// Call the showMessage method to display the message
myInstance.showMessage();
}
}
"MyClass," a Java class, uses the Singleton design pattern. The public static method "getInstance()" makes sure that just one instance of the class is created and makes sure that you may access it. The "Hello, World!" message is displayed when the singleton instance calls the "showMessage()" method.
Output
Hello, World!
Constructor Chaining in Java
- Constructor chaining in Java is a technique of calling one constructor from another constructor within the same class or subclass.
- It is used to minimize code duplication and improve readability by designing constructor methods with multiple parameters.
- This constructor chaining allows a programmer to set object properties quickly and effectively during object creation.
- Along with being able to pass arguments among constructors, constructor chaining can be used to create aliases for a constructor or even allow the use of default values when needed.
- By using constructor chaining, a programmer can easily utilize the full potential of Object-Oriented Programming in Java.
Constructor Chaining in Java: Example
public class Car {
private String make;
private String model;
private int year;
public Car() {
this("Unknown", "Unknown", 0);
}
public Car(String make) {
this(make, "Unknown", 0);
}
public Car(String make, String model) {
this(make, model, 0);
}
public Car(String make, String model, int year) {
this.make = make;
this.model = model;
this.year = year;
}
public void printCarDetails() {
System.out.println("Make: " + make);
System.out.println("Model: " + model);
System.out.println("Year: " + year);
}
public static void main(String[] args) {
Car car1 = new Car();
car1.printCarDetails();
Car car2 = new Car("Ford");
car2.printCarDetails();
Car car3 = new Car("Toyota", "Camry");
car3.printCarDetails();
Car car4 = new Car("Tesla", "Model S", 2022);
car4.printCarDetails();
}
}
This Java class, "Car," offers numerous constructors with various levels of parameterization to create car objects with make, model, and year properties. It shows how to create vehicle instances with various constructor overloads in the "main" method and uses the "printCarDetails" method to print their information.
Output
Make: Unknown
Model: Unknown
Year: 0
Make: Ford
Model: Unknown
Year: 0
Make: Toyota
Model: Camry
Year: 0
Make: Tesla
Model: Model S
Year: 2022
Super Constructor in Java
- Super Constructor in Java is a particular type of constructor that allows the subclass to invoke the Superclass constructor.
- It is used when an object is being inherited from another class and its subclasses need additional values that are specific to itself.
- Super Constructor can be used to create a thing of the Superclass with a different set of parameters than specified in its Superclass by calling Super().
- Super Constructor is useful for assigning different values to instance variables of Superclass, which may be required during subclass initialization.
- As a result, super constructors provide a greater level of flexibility while dealing with complex hierarchies.
Super Constructor in Java: Example
class Animal {
String name;
int age;
public Animal(String name, int age) {
this.name = name;
this.age = age;
}
public void displayInfo() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
}
class Dog extends Animal {
String breed;
public Dog(String name, int age, String breed) {
super(name, age);
this.breed = breed;
}
public void displayInfo() {
super.displayInfo();
System.out.println("Breed: " + breed);
}
}
public class Main {
public static void main(String[] args) {
Dog myDog = new Dog("Fido", 3, "Labrador");
myDog.displayInfo();
}
}
In the above-written code in Java Online Editor, there is a superclass called "Animal" and a subclass called "Dog." Name and age can be set in the "Animal" class' constructor, and the method "displayInfo" can report these details. The "breed" attribute is an extension of "Animal" added by the "Dog" class. The "Dog" instance is created, its attributes are initialized, and the data, including the breed, is displayed in the "main" method.
Output
Name: Fido
Age: 3
Breed: Labrador
Copy Constructor in Java
- Copy Constructor in Java is a special type of constructor used for creating a replica of an existing object.
- This type of constructor helps to reduce code redundancy and make programs more maintainable.
- Copy Constructors are a deep copy operation, meaning that all the member variables are copied by value rather than by reference.
- Copy Constructors are particularly useful when the user needs to create backup copies of objects before performing manipulation operations on them.
- Copy Constructor objects can also be used as handy return values from methods that create custom copies of classes.
- Copy Constructors can be quite powerful in achieving maximum code re-usability in Java applications.
Copy Constructor in Java: Example
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Copy constructor
public Person(Person other) {
this.name = other.name;
this.age = other.age;
}
public void display() {
System.out.println("Name: " + this.name);
System.out.println("Age: " + this.age);
}
}
public class Main {
public static void main(String[] args) {
Person person1 = new Person("John", 30);
Person person2 = new Person(person1); // Using copy constructor
person1.display();
person2.display();
}
}
This Java example creates a "Person" class with a copy constructor that allows you to duplicate the attributes of an existing "Person" object to create a new "Person" object. In the "main" method, it shows how to create "person1" and "person2" by copying "person1's" attributes, and then it displays the data for both "person1" and "person2."
Output
Name: John
Age: 30
Name: John
Age: 30
How to Copy Values Without Constructor in Java?
In Java, you can copy values from one object to another without using a constructor by implementing a method specifically for this purpose. One common approach is to create a method that takes an instance of the source object and copies its values to the destination object.
Example
class MyClass {
private int value;
// Getter and Setter methods
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
// Method to copy values
public void copyValues(MyClass source) {
this.value = source.getValue();
}
public static void main(String[] args) {
MyClass sourceObject = new MyClass();
sourceObject.setValue(10);
MyClass destinationObject = new MyClass();
destinationObject.copyValues(sourceObject);
System.out.println("Value in destination object: " + destinationObject.getValue());
}
}
Output
Value in destination object: 10
What Is Constructor Overloading in Java?
The process of defining multiple constructors of the same class is referred to as Constructor overloading in Java. The important thing is that each constructor should have a different signature or input parameters. In other words, constructor overloading in Java is a technique that allows a single class to have more than one constructor that varies by the list of arguments passed. Each overloaded constructor performs different tasks in the class.
The Java compiler identifies the overloaded constructors based on their parameter lists, parameter types, and the number of input parameters. Hence, the overloaded constructors should have different signatures. A constructor’s signature contains its name and parameter types.
Using this() in Constructor Overloading
All instance methods and constructors have an implicit parameter called ‘this’, which is used to refer to the current object. The current object is the object on which the method is invoked. We can use the ‘this’ reference to refer to the current object within any constructor or method.
In the following cases, the ‘this’ reference is used:
- When the names of the parameters are different from the instance variable names
- When a reference is to be passed to the current object and a parameter to another method
- When a constructor is to be invoked from another constructor.
Example
public class MyClass {
private int value;
// Default constructor
public MyClass() {
this.value = 0; // Initialize value to 0
}
// Constructor with one parameter
public MyClass(int value) {
this.value = value; // Initialize value to the provided parameter
}
// Constructor with two parameters
public MyClass(int value1, int value2) {
this.value = value1 + value2; // Initialize value to the sum of the two parameters
}
// Getter method
public int getValue() {
return value;
}
public static void main(String[] args) {
// Creating objects using different constructors
MyClass obj1 = new MyClass();
MyClass obj2 = new MyClass(5);
MyClass obj3 = new MyClass(3, 7);
// Displaying values
System.out.println("Value in obj1: " + obj1.getValue());
System.out.println("Value in obj2: " + obj2.getValue());
System.out.println("Value in obj3: " + obj3.getValue());
}
}
Output
Value in obj1: 0
Value in obj2: 5
Value in obj3: 10
Summary
After learning about Java Constructors, the constructor in Java, constructor in Java example, use of constructor in Java, java constructor we see that they are fundamental tools that every beginner programmer should understand. They allow us to create objects by passing in specific data needed, which helps reduce complexity and time spent coding. Although the syntax may be difficult for Java for beginners to grasp at first, with practice, it becomes second nature. Constructors are essential for all types of application development and can save developers both time and stress when used effectively.
FAQs
Q1. What are constructors in Java?
Q2. Why is a constructor used?
Q3. How many constructors can be used in Java?
Q4. Can we overload a constructor?
Q5. Can a constructor be private?
Q6. What is this () in Java constructor?
Q7. What is Constructor and Destructor in Java?
Java does not have explicit destructors like C++. Java uses automatic garbage collection to reclaim memory occupied by objects that are no longer referenced.