1 / 23

Initialization

Initialization. George Blank Subba Reddy Daka. Importance of Initialization. Java classes are initialized and have predictable default values. These values are stored in memory allocated on the heap when the class is instantiated Uninitialized data is a source of bugs!.

jabari
Download Presentation

Initialization

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Initialization George Blank Subba Reddy Daka

  2. Importance of Initialization • Java classes are initialized and have predictable default values. These values are stored in memory allocated on the heap when the class is instantiated • Uninitialized data is a source of bugs!

  3. 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.

  4. Default Initial Values • This table shows the default initial values for each of the variable types.

  5. 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.

  6. 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 typepublic CoffeeCup() {// Body of constructor}// ...}

  7. 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 cupCoffeeCup cup1 = new CoffeeCup();// Create a cup with 355 ml of coffee in itCoffeeCup cup2 = new CoffeeCup(355);} // Above requires constructor shown later } Constructors are not methods

  8. 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.

  9. 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) {//...}// ...}

  10. 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

  11. 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

  12. 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.

  13. 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.

  14. 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.

  15. 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.

  16. 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:

  17. // 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...}

  18. 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.

  19. 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)

  20. 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.

  21. 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) Example: Constructors in java.lang.String • String(String) • String(StringBuffer)

  22. 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.

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

More Related