Constructor in Java

Constructor in Java

Constructor in Java

Constructor in Java:

In Java, a constructor is a special method that is used to initialize objects of a class. Constructors have the same name as the class and no return type. Here are some key characteristics of constructors in Java:

  1. Syntax: The syntax for defining a constructor in Java is as follows:
				
					[access modifier] className([parameter list]) {
   // code to be executed
}

				
			
  • Access modifier: specifies the visibility of the constructor, such as public, private, or protected.
  • Class name: the name of the class for which the constructor is being defined.
  • Parameter list: a list of variables that are passed to the constructor as input.
  1. Purpose: The main purpose of a constructor is to initialize the instance variables of an object when it is created. Constructors can also perform other initialization tasks, such as allocating memory and setting default values.
  2. Default Constructor: If you don’t define any constructors in a class, Java provides a default constructor that takes no arguments and initializes all instance variables to their default values.
  3. Overloading Constructors: In Java, you can define multiple constructors for a class with different parameter lists. This is called constructor overloading.
  4. Constructor Chaining: In Java, you can call one constructor from another constructor using the this() This is called constructor chaining.

Here is an example of a simple constructor in Java:

				
					public class Example {
   int value;

   public Example() {
      value = 10;
   }

   public Example(int num) {
      value = num;
   }

   public static void main(String[] args) {
      Example obj1 = new Example();
      Example obj2 = new Example(20);

System.out.println("Value of obj1 is: " + obj1.value);
System.out.println("Value of obj2 is: " + obj2.value);
   }
} 

				
			

In this example, we define a class called Example with two constructors: one that takes no arguments and sets the value of value to 10, and another that takes an integer argument and sets the value of value to the argument. We then create two objects of the Example class using the two constructors and print their respective value variables. The output of this program would be:

				
					Value of obj1 is: 10
Value of obj2 is: 20

				
			
Join To Get Our Newsletter
Spread the love