Constructor is a special method in a class that is used to create and initialize an object of that class. When an object is created, the constructor is called and necessary initialization is performed. For example, the class MobilePhone has a constructor:
public class MobilePhone {
private int imeiNumber;
private String brandName;
//constructor
public MobilePhone (int number, String name) {
imeiNumber = number;
brandName = brand;
}
public String getBrandName() {
return brandName;
}
}
Here's an example of how you might use the MobilePhone class and its constructor:
MobilePhone myPhone = new MobilePhone(12345678, "Samsung");
In the above example, we first create a new MobilePhone object by calling the constructor with the arguments 12345678 and "Samsung". The constructor then initializes the object's imeiNumber field with the value 12345678 and brandName field with the value "Samsung".
In simple terms, constructors are a powerful feature of object-oriented programming that allows us to initialize an object with specific properties or perform certain operations every time an object is created. They provide a way to ensure that our objects are properly set up and ready to use. In Java, a constructor is a special type of method that has the following elements:
It's important to note that a constructor does not have a return type, even though it may appear similar to a method. When we call a constructor, it creates a new instance of the class and returns it. In this case, the return type of the constructor is implicit and it is not specified explicitly.
Additionally, if no constructor is defined in the class, Java will provide a default constructor with no parameters. However, it is also possible for developers to create their own constructors to define their own initialization logic.
In java, there are four types of constructors:
In Java, a no-argument constructor is a constructor that does not take any parameters. This means that when an object is created without passing any arguments to the constructor, the no-argument constructor is called.
Example
public class MobilePhone {
......
public MobilePhone() {
//perform some operations
}
.....
}
This constructor can be useful when you want to perform certain operations every time an object is created without any arguments. Note: If a class does not have any constructors explicitly defined, the Java compiler will automatically create a default no-argument constructor for the class.
In Java, a parameterized constructor is a constructor that takes one or more parameters. This type of constructor allows developers to initialize an object with specific values.
Example
public class MobilePhone {
private int imeiNumber;
private String brandName;
//parameterized constructor 1
public MobilePhone (int number, String name) {
imeiNumber = number;
brandName = brand;
}
//parameterized constructor 2
public MobilePhone (int number) {
imeiNumber = number;
}
public String getBrandName() {
return brandName;
}
}
In Java, a copy constructor is a constructor that creates a new object by copying the values of the properties from an existing object. In other words, it is used to create a new object that is an exact copy of an existing object but with a separate memory location.
A copy constructor takes an object of the same class as its parameter and uses the values of the properties of the existing object to initialize the properties of the new object.
Example
class MobilePhone {
private int imeiNumber;
private String brandName;
//other properties
........
//copy constructor
MobilePhone (MobilePhone object){
this.imeiNumber = object.imeiNumber;
this.brandName = object.brandName;
//other properties
}
......
}
It's important to note that, unlike some other programming languages, Java does not provide a built-in way to create a copy constructor. So, it is up to the developer to create one if needed. This can be useful in situations where you want to create a new object that is a copy of an existing object, but you don't want the new object to share the same memory location as the existing object.
In Java, a default constructor is a constructor that has no parameters and is automatically provided by the Java compiler if a class does not have any constructors defined. Default constructor is a no-argument constructor, as it does not take any arguments.
The default constructor initializes the object's properties with default values, such as 0 for numeric types, null for reference types, and false for boolean types. This can be useful in situations where you want to create an object with its properties set to these default values.
It's important to note that if a class has other constructors defined, the Java compiler will not provide a default constructor. In this case, developers can create a default constructor themselves if it is needed.
In Java, constructor overloading is the ability of a class to have multiple constructors with different parameter lists. This means that a class can have multiple constructors that have the same name but take different types and/or numbers of parameters.
This feature allows developers to provide different ways to create an object, each with its own specific set of parameters. This can be useful for creating objects with different initial property values or for providing different levels of complexity for object creation.
Example 1
class MobilePhone {
private int imeiNumber;
private String brandName;
MobilePhone(){
.....
}
MobilePhone(int number, String name){
.....
}
MobilePhone(MobilePhone mobile){
.....
}
MobilePhone(int number) {
.....
}
...
}
When a class has multiple constructors, the Java compiler uses the arguments passed to the constructor to determine which constructor to call. This process is known as constructor resolution.
In Java, constructor chaining is the practice of calling one constructor from another constructor within the same class. This can be achieved by using the keyword "this" followed by the parameters required by the constructor being called. Constructor chaining allows developers to reuse code and initialize objects in a consistent manner, while providing flexibility in how they are initialized. This is particularly useful when creating complex objects with multiple properties that need to be initialized in a specific order.
For example, suppose you have a class called "Person" with constructors that take different sets of arguments:
class Person {
private String name;
private int age;
private String address;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public Person(String name, int age, String address) {
this(name, age); // calls the constructor above
this.address = address;
}
}
In this example, the second constructor "Person(String name, int age, String address)" is calling the first constructor "Person(String name, int age)" using this(name, age) to avoid duplicating code and it also sets the address field. It's important to note that the call to another constructor must be the first statement in the constructor. So you can create an object of the Person class by either of the constructors:
Person p1 = new Person("Shubham", 30);
Person p2 = new Person("Shubham", 30, "New Delhi");
In this way, constructor chaining helps to reduce code duplication and make the code more organized and readable.
In Java, constructors can be used to implement dependency injection by passing in the required dependencies as parameters to the constructor. For example, consider a class Car that has a dependency on an Engine object. Instead of creating an Engine object inside the Car class, the Engine object can be passed in as a parameter to the Car class's constructor. This way, the Car class does not have to worry about creating its own Engine object and can instead rely on the object that is passed in.
class Engine { ... }
class Car {
private Engine engine;
public Car(Engine engine) {
this.engine = engine;
}
...
}
The singleton pattern is a design pattern that ensures that a class has only one instance and provides a global access point to that instance. One way to implement the singleton pattern in Java is by using a private constructor to ensure that only one instance of the class is created.
Here is an example of how to create a singleton class using a private constructor:
public class Singleton {
private static Singleton instance;
private Singleton(){}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
The private constructor ensures that the class can only be instantiated from within the class. The getInstance() method is used to return the single instance of the class and it creates an instance of the class if it doesn't already exist.
We can use private constructor to enforce security by implementing a user authentication process before creating an object. For example, in the following code, SecureObject class is only instantiated when the user credentials are valid. This will provide an additional layer of security to the application.
public class SecureObject {
private SecureObject() {
// private constructor
}
public static SecureObject createInstance(String username, String password) {
// Verify user credentials
boolean isAuthenticated = authenticate(username, password);
if (isAuthenticated) {
return new SecureObject();
} else {
throw new SecurityException("Invalid credentials");
}
}
private static boolean authenticate(String username, String password) {
// check credentials against a database or external service
// return true if valid, false otherwise
}
}
Driver code
SecureObject obj = SecureObject.createInstance("username", "password");
Constructors are an essential part of classes and, therefore, of Object-Oriented Programming. They are not considered special methods, but rather sub-routines that are invoked each time an object is created. In addition to the default constructor provided by the compiler, developers can also define their own constructors. A single class can have multiple constructors with different signatures, known as constructor overloading.
Enjoy learning, Enjoy oops!