initialization george blank subba reddy daka. importance of initialization java classes are...

23
Initialization George Blank Subba Reddy Daka

Post on 21-Dec-2015

217 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Initialization George Blank Subba Reddy Daka. Importance of Initialization Java classes are initialized and have predictable default values. These values

Initialization

George BlankSubba Reddy Daka

Page 2: Initialization George Blank Subba Reddy Daka. Importance of Initialization Java classes are initialized and have predictable default values. These values

Importance of Initialization

• Java classes are initialized and have Java classes are initialized and have predictable default values. These values predictable default values. These values are stored in memory allocated on the heap are stored in memory allocated on the heap when the class is instantiatedwhen the class is instantiated

• Uninitialized data is a source of bugs!Uninitialized data is a source of bugs!

Page 3: Initialization George Blank Subba Reddy Daka. Importance of Initialization Java classes are initialized and have predictable default values. These values

Types of Initialization

• Instance Initializers (also called instance initialization blocks).

• Instance variable initializers. • Constructors. • You should ensure that any of the three

types produce a valid state for newly created objects.

Page 4: Initialization George Blank Subba Reddy Daka. Importance of Initialization Java classes are initialized and have predictable default values. These values

Default Initial Values

• This table shows the default initial values for each of the variable types.

Type Default Value

boolean False

byte (byte) 0

short (short)0

int 0

long 0L

char \u 000

float 0.0f

double 0.0d

object information

null

Page 5: Initialization George Blank Subba Reddy Daka. Importance of Initialization Java classes are initialized and have predictable default values. These values

• If you don't explicitly initialize an instance variable, that variable will retain its default initial value when new returns its object reference. // In source packet in file

• // init/ex1/CoffeeCup.java// This class has no constructors or initializersclass CoffeeCup {    private int innerCoffee;    //...}As a result, when the reference to a new CoffeeCup object is first returned by new, the innerCoffee field will be its default initial value. Because innerCoffee is an int, its default initial value is zero.

Page 6: Initialization George Blank Subba Reddy Daka. Importance of Initialization Java classes are initialized and have predictable default values. These values

Constructors

• Constructor basicsIn the source file, a constructor looks like a method declaration in which the method has the same name as the class but has no return type. For example, here is a constructor declaration for class CoffeeCup:

•// In source packet in file init/ex2/CoffeeCup.javaclass CoffeeCup {    // Constructor looks like a method declaration    // minus the return type    public CoffeeCup() {        // Body of constructor    }    // ...}

Page 7: Initialization George Blank Subba Reddy Daka. Importance of Initialization Java classes are initialized and have predictable default values. These values

• When you instantiate an object with new, you must specify a constructor. For example, given the CoffeeCup class above that has two constructors, you could instantiate it in either of these two ways:

•// In source packet in file init/ex3/Example3.javaclass Example3 {    public static void main(String[] args) {

        // Create an empty cup        CoffeeCup cup1 = new CoffeeCup();

        // Create a cup with 355 ml of coffee in it        CoffeeCup cup2 = new CoffeeCup(355);    } // Above requires constructor shown later }

• Constructors are not methods

Page 8: Initialization George Blank Subba Reddy Daka. Importance of Initialization Java classes are initialized and have predictable default values. These values

Default constructors

• If you declare a class with no constructors, the compiler will automatically create a default constructor for the class. A default constructor takes no parameters.

• The compiler gives default constructors the same access level as their class.

Page 9: Initialization George Blank Subba Reddy Daka. Importance of Initialization Java classes are initialized and have predictable default values. These values

Instance initialization methods

When you compile a class, the Java compiler creates an instance initialization method for each constructor you declare in the source code of the class.

class CoffeeCup {    public CoffeeCup() {        //...    }    public CoffeeCup(int amount) {        //...    }    // ...}

Page 10: Initialization George Blank Subba Reddy Daka. Importance of Initialization Java classes are initialized and have predictable default values. These values

• The compiler would generate the following two instance initialization methods in the class file for class CoffeeCup, one for each constructor in the source file:

// In binary form in file init/ex8/CoffeeCup.class:public void (CoffeeCup this) {...}public void (CoffeeCup this, int amount) {...}

Instance initialization

Page 11: Initialization George Blank Subba Reddy Daka. Importance of Initialization Java classes are initialized and have predictable default values. These values

• In a constructor, you have the freedom to write as much code as needed to calculate an initial value. In an instance variable initializer, you have only an equals sign and one expression.

// In source packet in file init/ex9/CoffeeCup.javaclass CoffeeCup { private int innerCoffee; public CoffeeCup() {        innerCoffee = 355;    }    // ...}

Instance Variable Initializers

Page 12: Initialization George Blank Subba Reddy Daka. Importance of Initialization Java classes are initialized and have predictable default values. These values

Explanation

• // In source packet in file init/ex10/CoffeeCup.javaclass CoffeeCup {    private int innerCoffee = 355; // "= 355" is an initializer    // no constructor here    // ...}

• The right-hand side of the equals sign in an initializer can be any expression that evaluates to the type of the instance variable.

Page 13: Initialization George Blank Subba Reddy Daka. Importance of Initialization Java classes are initialized and have predictable default values. These values

• Instance initializers

An instance initializer, also called an instance initialization block is shown here with the CoffeeCup class innerCoffee variable initialized by an instance initializer:

// In source packet in file init/ex19/CoffeeCup.javaclass CoffeeCup {    private int innerCoffee;

    // The following block is an instance initializer    {        innerCoffee = 355;    }    // no constructor here    // ...}

This manner of initializing innerCoffee yields the same result as the previous two examples: innerCoffee is initialized to 355.

Page 14: Initialization George Blank Subba Reddy Daka. Importance of Initialization Java classes are initialized and have predictable default values. These values

• Initializers can't make forward references When you write an initializer (either an instance variable initializer or instance initializer), you must be sure not to refer to any instance variables declared textually after the variable being initialized. In other words, you can't make a forward reference from an initializer.

Page 15: Initialization George Blank Subba Reddy Daka. Importance of Initialization Java classes are initialized and have predictable default values. These values

• Initialization and inheritance When an object is initialized, all the instance variables defined in the object's class must be set to proper initial values.

Page 16: Initialization George Blank Subba Reddy Daka. Importance of Initialization Java classes are initialized and have predictable default values. These values

• Instance data of objectsEvery object, except class Object itself, has at least one superclass. When an object is created, the Java virtual machine allocates enough space for all the object's instance variables, which include all fields defined in the object's class and in all its superclasses. For example, consider the following classes:

Page 17: Initialization George Blank Subba Reddy Daka. Importance of Initialization Java classes are initialized and have predictable default values. These values

• // Declared in file Object.java (not In source packet)package java.lang;public class Object {    // Has no fields    // Has several methods, not shown...}

// In source packet in file init/ex14/Liquid.javaclass Liquid {    // Has two fields:    private int mlVolume;    private float temperature; // in Celsius    // Has several methods, not shown...}

// In source packet in file init/ex14/Coffee.javaclass Coffee extends Liquid {    // Has two fields:    private boolean swirling;    private boolean clockwise;    // Has several methods, not shown...}

Page 18: Initialization George Blank Subba Reddy Daka. Importance of Initialization Java classes are initialized and have predictable default values. These values

• Here you can see the data that must be allocated on the heap for a Coffee object. The part of the heap that is occupied by the instance data for the Coffee object is shown in the cyan color. Keep in mind that the actual manner of representing objects on the heap is an implementation detail of each particular Java virtual machine.

Page 19: Initialization George Blank Subba Reddy Daka. Importance of Initialization Java classes are initialized and have predictable default values. These values

• Order of initializationIn Java, the fields of an object are initialized starting with the fields declared in the base class and ending with the fields declared in the object's class. For a CoffeeCup object with the inheritance path shown in Figure 1, the order of initialization of fields would be:

• Object's fields (this will be quick, because there are none)

• Liquid's fields (mlVolume and temperature)

Page 20: Initialization George Blank Subba Reddy Daka. Importance of Initialization Java classes are initialized and have predictable default values. These values

• Coffee's fields (swirling and clockwise) • This base-class-first order aims to prevent

fields from being used before they are initialized to their proper (not default) values.

Page 21: Initialization George Blank Subba Reddy Daka. Importance of Initialization Java classes are initialized and have predictable default values. These values

Example: Constructors in java.lang.String

• String()• String(byte[])• String(byte[], int)• String(byte[], int , int)• String(byte[], int, int, int)• String(byte[], int, int, String)• String(byte[], String)• String(char[])• String(char[], int , int)

• String(String)• String(StringBuffer)

Page 22: Initialization George Blank Subba Reddy Daka. Importance of Initialization Java classes are initialized and have predictable default values. These values

Private and Protected Constructors

• Most constructors are public. There are some circumstances in which a private or protected constructor is used.

• For example, a private constructor is appropriate with a class using only static utility methods or constants, type safe enumerations, or a singleton class.

• Protected constructors are used to prevent instantiation outside the package.

Page 23: Initialization George Blank Subba Reddy Daka. Importance of Initialization Java classes are initialized and have predictable default values. These values

References

• THE JAVA HANDBOOK- PatrickNaughton• http://java.sun.com/• http://www.javaworld.net/