View RSS Feed

Java Object

Initializing Instance Members

Rate this Entry
by , 04-26-2012 at 04:55 PM (605 Views)
Usually code is being put for initialization of the instance variable, in constructor. Alternate ways present for initialization of the instance variables by using the constructor are: Final methods & Initializer blocks.
Instance variable’s initialize blocks look same as the static initializer blocks, but the static keyword is not present in it:
Java Code:
{
    // whatever code is needed for initialization goes here
}
Initializer blocks are being copied by the Java compiler to every constructor. Hence such approach could be used so that block of code could be shared b/w various constructors.

It is not possible to override a final method in a subclass. Final method usage to initialize the instance variable is shown by the following example:
Java Code:
class Whatever {
    private varType myVar = initializeInstanceVariable();
        
    protected final varType initializeInstanceVariable() {

        // initialization code goes here
    }
}

Submit "Initializing Instance Members" to Facebook Submit "Initializing Instance Members" to Digg Submit "Initializing Instance Members" to del.icio.us Submit "Initializing Instance Members" to StumbleUpon Submit "Initializing Instance Members" to Google

Categories
Tutorial

Comments