Constructor

Java constructors or constructors in Java is a terminology been used to construct something in our programs. A constructor in Java is a special method that is used to initialize objects. The constructor is called when an object of a class is created. It can be used to set initial values for object attributes. 

In Java, a constructor is a block of codes similar to the method. It is called when an instance of the class is created. At the time of calling the constructor, memory for the object is allocated in the memory. It is a special type of method which is used to initialize the object. Every time an object is created using the new() keyword, at least one constructor is called.

Note: It is not necessary to write a constructor for a class. It is because java compiler creates a default constructor if your class doesn’t have any.

How Constructors are Different From Methods in Java? 

  • Constructors must have the same name as the class within which it is defined while it is not necessary for the method in Java.
  • Constructors do not return any type while method(s) have the return type or void if does not return any value.
  • Constructors are called only once at the time of Object creation while method(s) can be called any number of times.

Need of Constructor

Think of a Box. If we talk about a box class then it will have some class variables (say length, breadth, and height). But when it comes to creating its object(i.e Box will now exist in the computer’s memory), then can a box be there with no value defined for its dimensions. The answer is no. 
So constructors are used to assign values to the class variables at the time of object creation, either explicitly done by the programmer or by Java itself (default constructor).

When is a Constructor called? 

Each time an object is created using a new() keyword, at least one constructor (it could be the default constructor) is invoked to assign initial values to the data members of the same class. 

The rules for writing constructors are as follows:

  • Constructor(s) of a class must have the same name as the class name in which it resides.
  • A constructor in Java can not be abstract, final, static, or Synchronized.
  • Access modifiers can be used in constructor declaration to control its access i.e which other class can call the constructor.

Types of Constructors in Java

Now is the correct time to discuss the types of the constructor, so primarily there are two types of constructors in java: 

  • No-argument constructor
  • Parameterized Constructor
  • Default constructor

1. No-argument constructor:

A constructor that has no parameter is known as the default constructor. If we don’t define a constructor in a class, then the compiler creates a default constructor(with no arguments) for the class. And if we write a constructor with arguments or no arguments then the compiler does not create a default constructor. 

class Constructor
{
   Constructor ()
{
   System.out.println("No argument constructor");
}
 public static void main (String[] args)
{
   Constructor no_argument = new Constructor();

}
}

Parameterized Constructor:

A constructor that has parameters is known as parameterized constructor. If we want to initialize fields of the class with our own values, then use a parameterized constructor.

Parameterized Constructor: A constructor that has parameters is known as parameterized constructor. If we want to initialize fields of the class with our own values, then use a parameterized constructor.

class Constructor
{
  int age, mobile_no; String name; char initial;


   Constructor (int a, String b, char c)
{
    age=a;
   name=b;
 initial=c;
   
}
 public static void main (String[] args)
{
   Constructor boy1 = new Constructor(24,"kithi",'A');
  
       boy1.details();
 }     
  void details()
{
  System.out.println("boy1 age is "+age);
  System.out.println("boy1 name is "+name);
  System.out.println("boy1 initial is "+initial);
}

}

Remember: Does constructor return any value?

There are no “return value” statements in the constructor, but the constructor returns the current class instance. We can write ‘return’ inside a constructor. –[TBD]

Now the most important topic that comes into play is the strong incorporation of OOPS with constructors known as constructor overloading. JustLike methods, we can overload constructors for creating objects in different ways. Compiler differentiates constructors on the basis of numbers of parameters, types of the parameters, and order of the parameters. 

class Constructor
{
  int age, mobile_no; String name; char initial;

   Constructor (int a, String b, char c, int d)
{
    age=a;
   name=b;
 initial=c;
mobile_no=d;
   
}

   Constructor (int a, String b, char c)
{
    age=a;
   name=b;
 initial=c;
   
}
 public static void main (String[] args)
{
   Constructor boy1 = new Constructor(24,"kithi",'A');
Constructor boy2 = newConstructor(20,"Arun",'S',12345);
       boy1.details();
      boy2.information();
 }     
  void details()
{
  System.out.println("boy1 age is "+age);
  System.out.println("boy1 name is "+name);
  System.out.println("boy1 initial is "+initial);
}
void information()
{
  System.out.println("boy2 age is "+age);
  System.out.println("boy2 name is "+name);
  System.out.println("boy2 initial is "+initial);
  System.out.println("boy2 phone number is"+mobile_no);
}


}
Java Default Constructor

If we do not create any constructor, the Java compiler automatically create a no-arg constructor during the execution of the program. This constructor is called default constructor.

class Constructor1
{ 
 int a;
 boolean b;
 char c;
public static void main (String[] args)
{
   Constructor1 girl = new Constructor1();
 
  System.out.println("default value of default constructor");
    System.out.println("int default value "+girl.a);
   System.out.println("boolean default value "+girl.b);
    System.out.println("char value "+girl.c);
}

}

Here, we haven’t created any constructors. Hence, the Java compiler automatically creates the default constructor.

The default constructor initializes any uninitialized instance variables with default values.

TypeDefault Value
booleanfalse
byte0
short0
int0
long0L
char\u0000
float0.0f
double0.0d
objectReference null
Important Notes on Java Constructors
  • Constructors are invoked implicitly when you instantiate objects.
  • The two rules for creating a constructor are:
    The name of the constructor should be the same as the class.
  • A Java constructor must not have a return type.
  • If a class doesn’t have a constructor, the Java compiler automatically creates a default constructor during run-time. The default constructor initializes instance variables with default values. For example, the int variable will be initialized to 0
  • Constructor types:
    No-Arg Constructor – a constructor that does not accept any arguments
    Parameterized constructor – a constructor that accepts arguments
    Default Constructor – a constructor that is automatically created by the Java compiler if it is not explicitly defined.
  • A constructor cannot be abstract or static or final.
  • A constructor can be overloaded but can not be overridden.

References:

https://www.programiz.com/java-programming/constructors

https://www.geeksforgeeks.org/constructors-in-java/

Leave a comment

Design a site like this with WordPress.com
Get started