Constructors in Java

 In the previous tutorials, we learnt about Java Methods and Method overloading, where you learnt how important methods are in a programming language and how to use them. In this tutorial, we are going going to learn about a special type of method, which is a very important aspect of Java or any Object Oriented Programming language, but completely hidden from us, i.e Constructor


This tutorial focusses on what is a Java Constructor, How constructor works and different types of Constructors.

What is a Constructor in Java?

A Java Constructor is a special type of method or a block of code, used to initialize objects or we can say to set initial values to object attributes. It is called automatically, whenever an instance of an object is created using that new keyword. 

We have learnt that whenever a class is created, no memory is allocated or used. But the actual memory allocation begins when we create objects, as object creation leads to constructor calling, which sets initial values to the instance variables, thus occupying some memory in Heap.

Java compiler provides each class with a default constructor by default. So if we do not declare any constructor in the code, the default constructor would always be present there and would be called at the time of object creation.

Though every constructor is a method, but is bound to few conditions, 

Rules for creating a constructor in Java: 

> Its name must be same as that of the name of the Class in which it is residing.
> It should not have any return type
> A constructor cannot be static, abstract, final or synchronised

Example: 

public class MyClass{
/* Constructor */
MyClass(){
//Statements
}
/* Methods */
void func1(){
//Statements
}
}

* Here the constructor for this class is MyClass(), having its name same as that of the class-name.
Constructors can have any set of statements inside it, that would be executed whenever the instance of class is created.
We can also specify the access modifier along with the Java constructors, they basically control object creation. This means, like suppose if we declare a constructor as private, then we cannot declare an instance of a class, outside that particular class.
By default, every constructor has default access mode.

Working of a constructor in Java

Each object created with the new keyword, invokes a constructor, depending upon the arguments passed. But if no argument is passed, then the default constructor is called, which initializes the instance variables with some default values for different data types, mentioned below.

> For variables with data types like int, long, short and byte, the default value is 0
> For float and double variables, default value is 0.0
> For character type variables, default value is \u0000 which is the Unicode value denoting null or 0 in decimal.
> For Boolean variables, default value is false
> For Class references default value is null

Example: 
public class constructorWorking {
    int n;         // default value: 0
    long l;         // default value: 0
    float f;        // default value: 0.0
    double d;       // default value: 0.0
    boolean b;    // default value: false
    char c;         // default value: \u0000 or space or null
 
    String str;        // default value: null
    Object obj;         // default value: null
 
    public void print() {
        System.out.println("integer = " + n);
        System.out.println("long = " + l);
        System.out.println("char = " + c);
        System.out.println("float = " + f);
        System.out.println("double = " + d);
        System.out.println("Boolean = " + b);
        System.out.println("String = " + str);
        System.out.println("object = " + obj);
    }
 
    public static void main(String[] args) {
        constructorWorking o1 = new constructorWorking();
        o1.print();
    }
 
}

OUTPUT
integer = 0
long = 0
char = 
float = 0.0
double = 0.0
Boolean = false
String = null
object = null

In case of printing character value, we get no output, but white spaces, which denotes null or '\u0000' in Unicode
Here no constructor is specified, so the default constructor that is provided by the Java Compiler, is called.

We can also set other values also, so that whenever a constructor is called, those values are set as initial values for the instance variables. 

Whenever we declare a constructor by our-self in the program, the default constructor provided by the Java Compiler is not called, and the one we declared is used as the default. This makes constructors more efficient and useful so as to initialise the class variables at the time of object creation, rather that explicitly initializing them.

Types of Constructors in Java

There are 2 types of constructors in Java: Default constructor(no-argument constructor) or the parameterized constructor.

> Default Constructor in Java 

A constructor that has no parameters associated with it, is known as default constructor or the no-arg constructor. They cannot accept any type of arguments passed to them. It can only set the above mentioned default values(set by the Java Compiler for the different data types) for the different instance variables.

But if we want to have some other values as defaults, we can hard code our constructor like this.

class MyClass2{
    /* Instance variables */
    int n;
    char s;
    int number;
    char section;
    
    /* Constructor */
    MyClass2(){
    number = 2;
    section = 'a';
    }
    }
    
    public class MyClass2Test{
    public static void main(String[] args){
        MyClass2 obj1 = new MyClass2();
        System.out.println("n = " + obj1.n + "    " + "s = " + obj1.s);
        System.out.println("Number = " + obj1.number + "    " + "Section = "+ obj1.section);
    }
    }

OUTPUT
n = 0    s = 
Number = 2  Section = a

Every time, the object is created. The instance variables for that particular instance will be initialized with Number = 2 and Section = a, because we have fixed there values, while others will still get the default values set by the Java Compiler so n=0 and s = '\u0000' (blank space). 

We cannot provide a flexible mechanism for initializing instance variables in this case. 

> Parameterized Constructor in Java

A constructors with a set of parameters is called a parameterized constructor. We can pass parameters to the constructor as we pass in methods, so as to initialize fields of our class, with any values(distinct or same) passed as arguments.

 Example:
class MyClass1{
    /* Instance variables */
    int rn;
    char section;
    
    /* Constructor */
    MyClass1(int rollNum, char sec ){
    rn = rollNum;
    section = sec;
    }
    }
    
    public class MyClass1Test{
    public static void main(String[] args){
    MyClass1 obj1 = new MyClass1(19,'c');
    MyClass1 obj2 = new MyClass1(29,'z');
    System.out.println(obj1.rn + "  " + obj1.section);
    System.out.println(obj2.rn + "  " + obj2.section);
    }
    }

OUTPUT
19  c
29  z

In obj1, we passed 19 and 'c' as arguments for the parameterized constructor. And it initialized the instance variables for obj1 as 19 and c. Similar is case for 29 and 'z' in obj2.
Hence, here we can change the initial values to be set, according to our need.


Ritish

Just a novice blogger

1 Comments

  1. its much intresting and quite amazing... visit to us also https://blogaddanews.blogspot.com/

    ReplyDelete
Post a Comment
Previous Post Next Post