Saturday 31 January 2015

Chapter 2.5 : Constructors in Java




Constructors in Java can be seen as Method in Class. But there is a big difference between Constructor and Method. These difference can be defined in terms of purpose,  syntax and Invocation.

Purpose of Constructor(Vs Method)

Constructor have only one purpose in life and that is to create an Instance of a Class. This instantiation includes memory allocation and member initialization(Optional).
In Contrast methods are used to provide some functionality in Java application. Method can not be used to create an Instance of a Class.


 

Syntax of Constructor(Vs Method)

/*
* Here Class name is  ConstructorExample, So constructor name needs to be the same.
*/
public class ConstructorExample {

    /*
     * As below signature has the name as Class name and it doesn't contain any
     * return value so it will be treated as Constructor of the class
     */
    public ConstructorExample() {
        System.out.println("Inside Constructor");
    }

    /*
     * Below method will be invoked only when it is invoked implicitly.
         * Method has return type along with Non Access Modifier
     */
    static void method() {
        System.out.println("This is in method");
    }
}

Syntax of constructor is different then Method in below aspects
  •  Constructor can not have Non Access Modifier while Method can have.
  • Constructor can not have return type(Not even void) while method must have one.
  • Constructor name be same as Class name while method can be different then class name.
  • As per Java naming convention method name should be camelcase while constructor name should start with caps letter.
Note*: A method can have the name of Class name.

Invocation of Constructor(Vs Method)

There is a difference between how a constructor and method can be called. Constructor can not be called explicitly, constructor will be invoked implicitly when instance of the class is getting created(Using new Keyword)

Constructor Invocation Example


/*
* Here Class name is  ConstructorExample, So constructor name needs to be the same.
*/
public class ConstructorExample {

    /*
     * As below signature has the name as Class name and it doesn't contain any
     * return value so it will be treated as Constructor of the class
     */
    public ConstructorExample() {
        System.out.println("Inside Constructor");
    }

    public static void main(String args[])
    {
        ConstructorExample cls = new ConstructorExample();
    }
}

//Output will be
//Inside Constructor

Method Invocation Example


/*
* Here Class name is  ConstructorExample, So constructor name needs to be the same.
*/
public class ConstructorExample {

    /*
     * As below signature has the name as Class name and it doesn't contain any
     * return value so it will be treated as Constructor of the class
     */
    public ConstructorExample() {
        System.out.println("Inside Constructor");
    }

    /*
     * Below method will be invoked only when it is invoked implicitly.
     */
    void method() {
        System.out.println("This is in method");
    }

    public static void main(String args[]) {
        ConstructorExample cls = new ConstructorExample();
        /*
         * Now method will be called explicitly as below. It will execute the
         * code within method.
         */
        cls.method();
    }
}

//Output would be
Inside Constructor
This is in method

A constructor in a class has the same name as the name of the given class. Constructor’s syntax does not include a return type, since constructors never return a value. Constructors may include parameters of various types. When the constructor is invoked using the new operator, the types must match those that are specified in the constructor definition. Java provides a default constructor which takes no arguments and performs no special actions or initializations, when no explicit constructors are provided.
The only action taken by the implicit default constructor is to call the superclass constructor using the super() call. Constructor arguments provide you with a way to provide parameters for the initialization of an object.


Constructor Rules
  • A constructor can’t have a return type.
  • Constructor must have the same name as class name.
  • Constructors can’t be marked static
  • Constructor can’t be marked Final or abstract
  •  Constructor can’t be overridden.
If a class defines an explicit constructor, it no longer has a default constructor to set the state of the objects. If such a class requires a default constructor, its implementation must be provided. Any attempt to call the default constructor will be a compile time error if an explicit default constructor is not provided in such a case.


Constructor Overloading:
Like methods, constructors can also be overloaded. Since the constructors in a class all have the same name as the class, their signatures are differentiated by their parameter lists.
It is possible to use this() construct, to implement local chaining of constructors in a class. The this() call in a constructor invokes the other constructor with the corresponding parameter list within the same class. Java requires that any this() call must occur as the first statement in a constructor.



Constructor Chaining:
Every constructor calls its superclass constructor. An implied super() is therefore included in each constructor which does not include either the this() function or an explicit super() call as its first statement. The super() statement invokes a constructor of the super class.
The implicit super() can be replaced by an explicit super(). The super statement must be the first statement of the constructor. The explicit super allows parameter values to be passed to the constructor of its superclass and must have matching parameter types A super() call in the constructor of a subclass will result in the call of the relevant constructor from the superclass, based on the signature of the call. This is called constructor chaining.
The super() construct as with this() construct: if used, must occur as the first statement in a constructor, and it can only be used in a constructor declaration. This implies that this() and super() calls cannot both occur in the same constructor. Just as the this() construct leads to chaining of constructors in the same class, the super() construct leads to chaining of subclass constructors to superclass constructors. if a constructor has neither a this() nor a super() construct as its first statement, then a super() call to the default constructor in the superclass is inserted.
 If a class only defines non-default constructors, then its subclasses will not include an implicit super() call. This will be flagged as a compile-time error. The subclasses must then explicitly call a superclass constructor, using the super() construct with the right arguments to match the appropriate constructor of the superclass.

No comments:

Post a Comment