Scrigroup - Documente si articole

Username / Parola inexistente      

Home Documente Upload Resurse Alte limbi doc  


AccessAdobe photoshopAlgoritmiAutocadBaze de dateCC sharp
CalculatoareCorel drawDot netExcelFox proFrontpageHardware
HtmlInternetJavaLinuxMatlabMs dosPascal
PhpPower pointRetele calculatoareSqlTutorialsWebdesignWindows
WordXml

AspAutocadCDot netExcelFox proHtmlJava
LinuxMathcadPhotoshopPhpSqlVisual studioWindowsXml

Constructor initialization

java

+ Font mai mare | - Font mai mic



DOCUMENTE SIMILARE

Trimite pe Messenger
Casting operators
Windowed applications
The generic collection library
Calling constructors from constructors
Alternatives to action
Introduction to Seam
Specifying initialization
Your first Java program
Coding style
Handling Text, Dialogs, And Lists


Constructor initialization

The constructor can be used to perform initialization, and this gives you greater flexibility in your programming since you can call methods and perform actions at run time to determine the initial values. Thereís one thing to keep in mind, however: you arenít precluding the automatic initialization, which happens before the constructor is entered. So, for example, if you say:




class Counter
// . . .

then i will first be initialized to zero, then to 7. This is true with all the primitive types and with object handles, including those that are given explicit initialization at the point of definition. For this reason, the compiler doesnít try to force you to initialize elements in the constructor at any particular place, or before they are used Ė initialization is already guaranteed.

Order of initialization

Within a class, the order of initialization is determined by the order that the variables are defined within the class. Even if the variable definitions are scattered throughout in between method definitions, the variables are initialized before any methods can be called Ė even the constructor. For example:

//: OrderOfInitialization.java

// Demonstrates initialization order.

// When the constructor is called, to create a

// Tag object, you'll see a message:

class Tag

class Card

Tag t2 = new Tag(2); // After constructor

void f()

Tag t3 = new Tag(3); // At end

public class OrderOfInitialization

In Card, the definitions of the Tag objects are intentionally scattered about to prove that theyíll all get initialized before the constructor is entered or anything else can happen. In addition, t3 is re-initialized inside the constructor. The output is:

Tag(1)

Tag(2)

Tag(3)

Card()

Tag(33)

f()

Thus, the t3 handle gets initialized twice, once before and once during the constructor call. (The first object is dropped, so it can be garbage-collected later.) This might not seem efficient at first, but it guarantees proper initialization Ė what would happen if an overloaded constructor were defined that did not initialize t3 and there wasnít a ďdefaultĒ initialization for t3 in its definition?

Static data initialization

When the data is static the same thing happens; if itís a primitive and you donít initialize it, it gets the standard primitive initial values. If itís a handle to an object, itís null unless you create a new object and attach your handle to it.

If you want to place initialization at the point of definition, it looks the same as for non-statics. But since thereís only a single piece of storage for a static, regardless of how many objects are created the question of when that storage gets initialized arises. An example makes this question clear:

//: StaticInitialization.java

// Specifying initial values in a

// class definition.

class Bowl

void f(int marker)

class Table

void f2(int marker)

static Bowl b2 = new Bowl(2);

class Cupboard

void f3(int marker)

static Bowl b5 = new Bowl(5);

public class StaticInitialization

static Table t2 = new Table();

static Cupboard t3 = new Cupboard();

Bowl allows you to view the creation of a class, and Table and Cupboard create static members of Bowl scattered through their class definitions. Note that Cupboard creates a non-static Bowl b3 prior to the static definitions. The output shows what happens:

Bowl(1)

Bowl(2)

Table()

f(1)

Bowl(4)

Bowl(5)

Bowl(3)

Cupboard()

f(2)

Creating new Cupboard() in main

Bowl(3)

Cupboard()

f(2)

Creating new Cupboard() in main

Bowl(3)

Cupboard()

f(2)

f2(1)

f3(1)



The static initialization occurs only if itís necessary. If you donít create a Table object and you never refer to Table.b1 or Table.b2, the static Bowl b1 and b2 will never be created. However, they are created only when the first Table object is created (or the first static access occurs). After that, the static object is not re-initialized.

The order of initialization is statics first, if they havenít already been initialized by a previous object creation, and then the non-static objects. You can see the evidence of this in the output.

Itís helpful to summarize the process of creating an object. Consider a class called Dog:

The first time an object of type Dog is created, or the first time a static method or static field of class Dog is accessed, the Java interpreter must locate Dog.class, which it does by searching through the classpath.

As Dog.class is loaded (which creates a Class object, which youíll learn about later), all of its static initializers are run. Thus, static initialization takes place only once, as the Class object is loaded for the first time.

When you create a new Dog( ), the construction process for a Dog object first allocates enough storage for a Dog object on the heap.

This storage is wiped to zero, automatically setting all the primitives in Dog to their default values (zero for numbers and the equivalent for boolean and char).

Any initializations that occur at the point of field definition are executed.

Constructors are executed. As you shall see in Chapter 6, this might actually involve a fair amount of activity, especially when inheritance is involved.

Explicit static initialization

Java allows you to group other static initializations inside a special ďstatic construction clauseĒ (sometimes called a static block) in a class. It looks like this:

class Spoon
// . . .

So it looks like a method, but itís just the static keyword followed by a method body. This code, like the other static initialization, is executed only once, the first time you make an object of that class or you access a static member of that class (even if you never make an object of that class). For example:

//: ExplicitStatic.java

// Explicit static initialization

// with the 'static' clause.

class Cup

void f(int marker)

class Cups

Cups()

public class ExplicitStatic

static Cups x = new Cups(); // (2)

static Cups y = new Cups(); // (2)
} ///:~

The static initializers for Cups will be run when either the access of the static object c1 occurs on the line marked (1), or if line (1) is commented out and the lines marked (2) are uncommented. If both (1) and (2) are commented out, the static initialization for Cups never occurs.

Non-static instance initialization

Java 1.1 provides a similar syntax for initializing non-static variables for each object. Hereís an example:

//: Mugs.java

// Java 1.1 'Instance Initialization'

class Mug

void f(int marker)

public class Mugs

Mugs()

public static void main(String[] args)

You can see that the instance initialization clause:

looks exactly like the static initialization clause except for the missing static keyword. This syntax is necessary to support the initialization of anonymous inner classes (see Chapter 7).



In contrast, C++ has the constructor initializer list that causes initialization to occur before entering the constructor body, and is enforced for objects. See Thinking in C++.






Politica de confidentialitate



DISTRIBUIE DOCUMENTUL

Comentarii


Vizualizari: 415
Importanta: rank

Comenteaza documentul:

Te rugam sa te autentifici sau sa iti faci cont pentru a putea comenta

Creaza cont nou

Termeni si conditii de utilizare | Contact
© SCRIGROUP 2022 . All rights reserved

Distribuie URL

Adauga cod HTML in site