Monday, December 7, 2015

Constructor

Constructor

Constructor in java is a special type of method that is used to initialize the object.
Java constructor is invoked at the time of object creation. It constructs the values i.e. provides data for the object that is why it is known as constructor.
The purpose of a class constructor is to initialize the class fields. A class constructor is automatically called when an instance of  a class is created.

Rules for creating java constructor

There are basically two rules defined for the constructor.
  1. Constructor name must be same as its class name
  2. Constructor must have no explicit return type

Types of java constructors

There are two types of constructors:
  1. Default constructor (no-arg constructor)
  2. Parameterized constructor
java constructor

Java Default Constructor

Constructors are not mandatory. If we do not provide a constructor, a default parameter less constructor is automatically provided. A constructor that have no parameter is known as default constructor.

Syntax of default constructor:

  1. <class_name>(){}  

Example of default constructor

In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the time of object creation.
  1. class Bike1{  
  2. Bike1(){System.out.println("Bike is created");}  
  3. public static void main(String args[]){  
  4. Bike1 b=new Bike1();  
  5. }  
  6. }  
Test it Now Output:
Bike is created

Rule: If there is no constructor in a class, compiler automatically creates a default constructor.

default constructor

Q) What is the purpose of default constructor?

Default constructor provides the default values to the object like 0, null etc. depending on the type.

Example of default constructor that displays the default values

  1. class Student3{  
  2. int id;  
  3. String name;  
  4.   
  5. void display(){System.out.println(id+" "+name);}  
  6.   
  7. public static void main(String args[]){  
  8. Student3 s1=new Student3();  
  9. Student3 s2=new Student3();  
  10. s1.display();  
  11. s2.display();  
  12. }  
  13. }  
Test it Now Output:
0 null
0 null
Explanation:In the above class,you are not creating any constructor so compiler provides you a default constructor.Here 0 and null values are provided by default constructor.

Java parameterized constructor

A constructor that have parameters is known as parameterized constructor.

Why use parameterized constructor?

Parameterized constructor is used to provide different values to the distinct objects.

Example of parameterized constructor

In this example, we have created the constructor of Student class that have two parameters. We can have any number of parameters in the constructor.
  1. class Student4{  
  2.     int id;  
  3.     String name;  
  4.       
  5.     Student4(int i,String n){  
  6.     id = i;  
  7.     name = n;  
  8.     }  
  9.     void display(){System.out.println(id+" "+name);}  
  10.    
  11.     public static void main(String args[]){  
  12.     Student4 s1 = new Student4(111,"Karan");  
  13.     Student4 s2 = new Student4(222,"Aryan");  
  14.     s1.display();  
  15.     s2.display();  
  16.    }  
  17. }  
Test it Now Output:
111 Karan
222 Aryan

Constructor Overloading in Java

Constructor overloading is a technique in Java in which a class can have any number of constructors that differ in parameter lists.The compiler differentiates these constructors by taking into account the number of parameters in the list and their type.

Example of Constructor Overloading

  1. class Student5{  
  2.     int id;  
  3.     String name;  
  4.     int age;  
  5.     Student5(int i,String n){  
  6.     id = i;  
  7.     name = n;  
  8.     }  
  9.     Student5(int i,String n,int a){  
  10.     id = i;  
  11.     name = n;  
  12.     age=a;  
  13.     }  
  14.     void display(){System.out.println(id+" "+name+" "+age);}  
  15.    
  16.     public static void main(String args[]){  
  17.     Student5 s1 = new Student5(111,"Karan");  
  18.     Student5 s2 = new Student5(222,"Aryan",25);  
  19.     s1.display();  
  20.     s2.display();  
  21.    }  
  22. }  
Test it Now Output:
111 Karan 0
222 Aryan 25

Difference between constructor and method in java

There are many differences between constructors and methods. They are given below.
Java ConstructorJava Method
Constructor is used to initialize the state of an object.Method is used to expose behaviour of an object.
Constructor must not have return type.Method must have return type.
Constructor is invoked implicitly.Method is invoked explicitly.
The java compiler provides a default constructor if you don't have any constructor.Method is not provided by compiler in any case.
Constructor name must be same as the class name.Method name may or may not be same as class name.

Java Copy Constructor

There is no copy constructor in java. But, we can copy the values of one object to another like copy constructor in C++.
There are many ways to copy the values of one object into another in java. They are:
  • By constructor
  • By assigning the values of one object into another
  • By clone() method of Object class
In this example, we are going to copy the values of one object into another using java constructor.
  1. class Student6{  
  2.     int id;  
  3.     String name;  
  4.     Student6(int i,String n){  
  5.     id = i;  
  6.     name = n;  
  7.     }  
  8.       
  9.     Student6(Student6 s){  
  10.     id = s.id;  
  11.     name =s.name;  
  12.     }  
  13.     void display(){System.out.println(id+" "+name);}  
  14.    
  15.     public static void main(String args[]){  
  16.     Student6 s1 = new Student6(111,"Karan");  
  17.     Student6 s2 = new Student6(s1);  
  18.     s1.display();  
  19.     s2.display();  
  20.    }  
  21. }  
Test it Now Output:
111 Karan
111 Karan

Copying values without constructor

We can copy the values of one object into another by assigning the objects values to another object. In this case, there is no need to create the constructor.
  1. class Student7{  
  2.     int id;  
  3.     String name;  
  4.     Student7(int i,String n){  
  5.     id = i;  
  6.     name = n;  
  7.     }  
  8.     Student7(){}  
  9.     void display(){System.out.println(id+" "+name);}  
  10.    
  11.     public static void main(String args[]){  
  12.     Student7 s1 = new Student7(111,"Karan");  
  13.     Student7 s2 = new Student7();  
  14.     s2.id=s1.id;  
  15.     s2.name=s1.name;  
  16.     s1.display();  
  17.     s2.display();  
  18.    }  
  19. }  
Test it Now Output:
111 Karan
111 Karan

 

Introduction

Constructors have a very special meaning to Compiler and CLR but sometimes its flow seems difficult for a developer. Today I will explain simple but important insights of Constructor.

So, What is a Constructor?

A Constructor is a special method in a class/struct with the same name as that of class/struct without any return type, used to initialize fields and members of a class/struct;
A constructor can only be called by:
  • Compiler using New keyword to initialize a class/struct.
  • Another constructor of same class/struct using :this() keyword.
  • Constructors of derived class using :base() keyword.

Types of Constructor in C#?

  • Default constructor
  • Parameterized constructor
  • Instance constructor
  • Static constructor
  • Private constructor

Default Constructor?

  1. A Constructor with no parameter is called Default Constructor.
  2. Default Constructor is called by compiler when no arguments are passed to New operator while creating an object of class or struct.
  3. If there is no constructor in a Non-Static class, a Public Default Constructor is provided by compiler so that a class can be instantiated.
  4. A Struct cannot have an explicit Default Constructor (We cannot define an explicit Default Constructor in a struct), but it is always provided by compiler to initialize each field of struct to its default value.

Parameterized Constructor?

  1. A constructor with parameters is called parameterized Constructor.
  2. A Class or Struct can have multiple parameterized constructors as long as they have different method signature. They follow the same concept of method overloading.
  3. Compiler provides Default Constructors only if there is no constructor (Default or Parameterized) defined in a class.
  4. Parameterized Constructors can exist even without the existence of Default Constructors.

Static Constructor?

  1. To initialize a Static Class or Static variables in Non-Static Class, Static Constructors are used
  2. Access Modifiers are not allowed on Static Constructors
  3. Static Constructors cannot be parameterized
  4. There can be only one Static Constructors per class
  5. Static Constructors cannot have an explicit 'this' or 'base' constructor call, i.e., Static Constructors cannot be called directly
  6. Static Constructors are called automatically before the first instance of a class is created or any static member is referenced
  7. Static Constructors are called only once in the lifetime of a class

Private Constructor?

  1. A constructor becomes a private constructor when we declare with private access specifier.
  2. Private Constructors can neither be instantiated nor inherited from other class.
  3. Object of class can only be created in the class itself.
  4. Microsoft recommends its uses to implement Singleton Pattern.

Constructor Chaining?

  1. A constructor can make a call to another constructor of the same class or of base class;
  2. Since one constructor can invoke another, this sometimes can cause execution of multiple constructors and is referred to as Constructor chaining;
  3. If class is not derived from any other class, below would be the chain:
    1. Static Constructor
    2. Instance Constructor
  4. If a class is derived from any other class, below would be the chain:
    1. Derived Static Constructor
    2. Base Static Constructor
    3. Base Instance Constructor
    4. Derived Instance Constructor
I hope I have covered all topics related to constructor. Please let me know if I have missed any or if you need more explanation or examples.
!! Happy programming !!

 

Introduction

Broadly speaking, a constructor is a method in the class which gets executed when its object is created. Usually, we put the initialization code in the constructor. Writing a constructor in the class is damn simple, have a look at the following sample:
public class mySampleClass
{
    public mySampleClass()
    {
        // This is the constructor method.
    }
    // rest of the class members goes here.
}
When the object of this class is instantiated, this constructor will be executed. Something like this:
mySampleClass obj = new mySampleClass()
// At this time the code in the constructor will // be executed

Constructor Overloading

C# supports overloading of constructors, that means, we can have constructors with different sets of parameters. So, our class can be like this:
public class mySampleClass
{
    public mySampleClass()
    {
        // This is the no parameter constructor method.
        // First Constructor
    }

    public mySampleClass(int Age)
    {
        // This is the constructor with one parameter.
        // Second Constructor
 
    }

    public mySampleClass(int Age, string Name)
    {
        // This is the constructor with two parameters.
        // Third Constructor
    }

    // rest of the class members goes here.
}
Well, note here that call to the constructor now depends on the way you instantiate the object. For example:
mySampleClass obj = new mySampleClass()
// At this time the code of no parameter  
// constructor (First Constructor)will be executed
 
mySampleClass obj = new mySampleClass(12)
// At this time the code of one parameter  
// constructor(Second Constructor)will be 
// executed.
The call to the constructors is completely governed by the rules of overloading here.

Calling Constructor from another Constructor

You can always make a call to one constructor from within another. Say, for example:
public class mySampleClass
{
    public mySampleClass(): this(10)
    {
        // This is the no parameter constructor method.
        // First Constructor
    }

    public mySampleClass(int Age) 
    {
        // This is the constructor with one parameter.
        // Second Constructor
    }
}
Very first of all, let us see what is this syntax:
public mySampleClass(): this(10)
Here, this refers to same class, so when we say this(10), we actually mean execute the public mySampleClass(int Age) method. The above way of calling the method is called initializer. We can have at the most one initializer in this way in the method.
Another thing which we must know is the execution sequence i.e., which method will be executed when. Here, if I instantiate the object as:
mySampleClass obj = new mySampleClass()
Then the code of public mySampleClass(int Age) will be executed before the code of mySampleClass(). So, practically the definition of the method:
public mySampleClass(): this(10)
{
    // This is the no parameter constructor method.
    // First Constructor
}
is equivalent to:
public mySampleClass()
{
    mySampleClass(10) 
    // This is the no parameter constructor method.
    // First Constructor
}
Note: Above (just above this line) code is mentioned there for pure analogy and will not compile. The intention here is to tell the flow of execution if initializers are used.
We cannot make an explicit call to the constructors in C#, treating them as if any simple method, for example: statement mySampleClass(10) in the above code will not work. The only way you can call one constructor from another is through initializers.
For the VB.NET programmers: you can make the call to another constructor of the same class by the syntax Me.New(param list), but it should be the first line of your calling constructor method. So ultimately, the code of the called constructor runs prior to the code of the calling constructor, which is same as initializers here.
Note that only this and base (we will see it further) keywords are allowed in initializers, other method calls will raise an error.
This is sometimes called Constructor chaining.
Huff… Simple thing made tough, but this is how it is. Anyway, let us proceed further.

Behavior of Constructors in Inheritance

Let us first create the inherited class.
public class myBaseClass
{
    public myBaseClass()
    {
        // Code for First Base class Constructor
    }

    public myBaseClass(int Age)
    {
        // Code for Second Base class Constructor
    }

    // Other class members goes here
}

public class myDerivedClass : myBaseClass
// Note that I am inheriting the class here.
{
    public myDerivedClass()
    {
        // Code for the First myDerivedClass Constructor.
    }

    public myDerivedClass(int Age):base(Age)
    {
        // Code for the Second myDerivedClass Constructor.
    }

    // Other class members goes here
}
Now, what will be the execution sequence here:
If I create the object of the derived class as:
myDerivedClass obj = new myDerivedClass()
Then the sequence of execution will be:
  1. public myBaseClass() method.
  2. and then public myDerivedClass() method.
Note: If we do not provide initializer referring to the base class constructor then it executes the no parameter constructor of the base class.
Note one thing here: we are not making any explicit call to the constructor of base class neither by initializer nor by the base keyword, but it is still executing. This is the normal behavior of the constructor.
If I create an object of the derived class as:
myDerivedClass obj = new myDerivedClass(15)
Then the sequence of execution will be:
  1. public myBaseClass(int Age) method
  2. and then public myDerivedClass(int Age) method
Here, the new keyword base has come into picture. This refers to the base class of the current class. So, here it refers to the myBaseClass. And base(10) refers to the call to myBaseClass(int Age) method.
Also note the usage of Age variable in the syntax: public myDerivedClass(int Age):base(Age). [Understanding it is left to the reader].

Private Constructors

Private constructors, the constructors with the "private" access modifier, are a bit special case. It is because we can neither create the object of the class, nor can we inherit the class with only private constructors. But yes, we can have the set of public constructors along with the private constructors in the class and the public constructors can access the private constructors from within the class through constructor chaining.
Say for example, my class is something like this :
public class myClass
{
    private MyClass()
    {
        Console.WriteLine("This is no parameter Constructor");
    }

    public MyClass(int var):this()
    {
        Console.WriteLine("This is one parameter Constructor");
    }    
    // Other class methods goes here
}
Then we can create the object of this class by the statement:
MyClass obj = new MyClass(10);
The above statement will work fine, but the statement
MyClass obj = new MyClass();
will raise an error : 'Constructors.MyClass.MyClass()' is inaccessible due to its protection level
It is possible to have the class with only the private constructors. But yes as I said, such class can neither be instantiated nor be inherited. If we try to inherit the class with only private constructors then we will get the same error as above. Also recall, once you provide constructor from your side the compiler will not add the no-parameter public constructor to your class.
Well, one of the usage scenarios of such class could be – when you have only static members in the class and you don't need to instantiate it.
Phew… lost… Anything left in constructors? Yes, Static Constructors. Ha!! Now, what are they? Let us see..

Static Constructors

This is a new concept introduced in C#. By new here, I mean that it was not available for the C++ developers. This is a special constructor and gets called before the first object is created of the class. The time of execution cannot be determined, but it is definitely before the first object creation - could be at the time of loading the assembly.
The syntax of writing the static constructors is also damn simple. Here it is:
public class myClass
{
    static myClass()
    {
        // Initialization code goes here.
        // Can only access static members here.
    }
    // Other class methods goes here
}
Notes for Static Constructors:
  1. There can be only one static constructor in the class.
  2. The static constructor should be without parameters.
  3. It can only access the static members of the class.
  4. There should be no access modifier in static constructor definition.
Ok fine, all the above points are fine, but why is it like that? Let us go step by step here.
Firstly, the call to the static method is made by the CLR and not by the object, so we do not need to have the access modifier to it.
Secondly, it is going to be called by CLR, who can pass the parameters to it, if required. So we cannot have parameterized static constructor.
Thirdly, non-static members in the class are specific to the object instance. So static constructor, if allowed to work on non-static members, will reflect the changes in all the object instances, which is impractical. So static constructor can access only static members of the class.
Fourthly, overloading needs the two methods to be different in terms of methods definition, which you cannot do with Static Constructors, so you can have at the most one static constructor in the class.
Now, one question raises here, can we have two constructors as:
public class myClass
{
    static myClass()
    {
        // Initialization code goes here.
        // Can only access static members here.
    }
    public myClass()
    {
        // Code for the First myDerivedClass Constructor.
    }

    // Other class methods goes here
}
This is perfectly valid, though doesn't seem to be in accordance with overloading concepts. But why? Because the time of execution of the two methods are different. One is at the time of loading the assembly and one is at the time of object creation.

Constructors FAQs

  1. Is the constructor mandatory for a class? Yes, it is mandatory to have the constructor in the class and that too should be accessible for the object i.e., it should have a proper access modifier. Say, for example, we have only private constructor(s) in the class and if we are interested in instantiating the class, i.e., want to create an object of the class, then having only private constructor will not be sufficient and in fact it will raise an error. So, proper access modifies should be provided to the constructors.
  2. What if I do not write the constructor? In such case, the compiler will try to supply the no parameter constructor for your class, behind the scene. Compiler will attempt this only if you do not write the constructor for the class. If you provide any constructor (with or without parameters), then compiler will not make any such attempt.
  3. What if I have the constructor public myDerivedClass(), but not the public myBaseClass()? It will raise an error. If either the no parameter constructor is absent or it is in-accessible (say it is private), it will raise an error. You will have to take the precaution here.
  4. Can we access static members from the non-static (normal) constructors? Yes, we can. There is no such restriction on non-static constructors. But there is one on static constructors that it can access only static members.

 

Destructors in C#:

Destructors have the same name as the class with ~ symbol infront of them. They don't take any parameters and do not return a value. Destructors are places where you could put code to release any resources your class was holding during its lifetime.They are normally called when the c# garbage collector decides to clean your object from your memory.

Destructors syntax:
                          ~class_name(){} 
 

No comments:

Post a Comment