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.

Chapter 2.4 : Class and Object



How to Create an Object of Class

To Create Object of  a class <new> Keyword can be used.
Syntax:
<Class_Name>   ClassObjectReference = new <Class_Name>();
Here constructor of the class(Class_Name) will get executed and Object will get created(ClassObjectRefrence will hold the refrence of created object in memory).


How to Access Member of a Class

(ClassObjectReference.member ). You call a method of an object by naming the object followed by a period (dot), followed by the name of the method and its argument list, like this:

objectName.methodName(arg1, arg2, arg3).


 

Class Variables – Static Fields

Class variables also know as Static fields share characteristics across all objects within a class. When you declare a field to be static, only a single instance of the associated variable is created, which is common to all the objects of that class. Hence when one object changes the value of a class variable, it affects all objects of the class. We can access a class variable by using the name of the class, and not necessarily using a reference to an individual object within the class. Static variables can be accessed even though no objects of that class exist. It is declared using static keyword.


Class Methods – Static Methods

Class methods, similar to Class variables can be invoked without having an instance of the class. Class methods are often used to provide global functions for Java programs. For example, methods in the java.lang.Math package are class methods. You cannot call non-static methods from inside a static method.
 JavaObjects
The Object Class is the super class for all classes in Java. Some of the object class methods are
equals
toString()
wait()
notify()
notifyAll()
hashcode()
clone()

An object is an instance of a class created using a new operator. The new operator returns a reference to a new instance of a class. This reference can be assigned to a reference variable of the class. The process of creating objects from a class is called instantiation. An object encapsulates state and behavior.
An object reference provides a handle to an object that is created and stored in memory. In Java, objects can only be manipulated via references, which can be stored in variables.
Creating variables of your class type is similar to creating variables of primitive data types, such as integer or float. Each time you create an object, a new set of instance variables comes into existence which defines the characteristics of that object. If you want to create an object of the class and have the reference variable associated with this object, you must also allocate memory for the object by using the new operator. This process is called instantiating an object or creating an object instance.
When you create a new object, you use the new operator to instantiate the object. The new operator returns the location of the object which you assign o a reference type.

Chapter 2.3 : Java Class & Object




Class is a template for creating objects which defines its state and behaviour. A class contains field and method to define the state and behavior of its Object. 

Syntax for Declaring Class:

<Access Modifier> class <Class_Name> extends
                 <Super_Class_Name> implements <Interface_Name>
Access modifier define who in java world can access this Class and member of the class.
Class_Name
Unique name for the class in specific package.
Super_Class_Name
Name of class which above class extends.(Super class of the given class)
Interface_Name
Name of Inerface ‘Class_Name‘ class implements.(Implements keyword is used for this purpose)

Internal structure of Class

<Access Modifier> class <Class_Name> extends <Super_Class_Name> implements <Interface_Name>{
    <static initilizar block>
    <ananymous block>
    <constructor declarations>
    <field declarations (Static and Non-Static)>
    <method declarations (Static and Non-Static)>
    <Inner class declarations>
    <nested interface declarations>
    Access variables inside class
}


 

Example of  Java Class

Classes are written in Java source file. A source file can contain more then one Java class. Below are the rules related to Java source code file.
/*
* This is Multi Line Comment and Comment can appear at any place
*/
package com.jbt;

import java.lang.*;

/*
* As this file contains public class. Then the name of this file should be TestClass.java
*/
public class TestClass {
    public int i;
    static {
        System.out.println("This is static block");
    }

    {
        System.out.println("This is ananuymous block");
    }

    TestClass() {
        System.out.println("This is constructor");
    }

    void methid() {
        System.out.println("This is method");
    }

}

class AnotherClass {
}