In-depth introduction to Java Object Initialization _java

Source: Internet
Author: User

Objective

In Java, an object must be properly initialized before it can be used, as specified by the Java specification.

Initialize automatically (default)

All the basic data members of a class are initialized, and the following example can be used to view these defaults:

Class default{
  Boolean t;
  char c;
  byte B;
  Short S;
  int i;
  Long L;
  float F;
  Double D;
  public void Show () {
    System.out.println ("base type  initialization value \ n" +
            "boolean<----->" + t + "\ n" + "
            char") <-----> "+ c +" \ n "+
            " byte<-----> "+ B +" \ n "+
            " short<-----> "+ S +" \ n "+
            " int<-----  > "+ i +" \ n "+
            " long<-----> "+ L +" \ n "+
            " float<-----> "+ f +" \ n "+
            " double<-----> " + D + "\ n"
    )

  ;
}
public class InitValue {public
  static void Main (string[] args) {
    default d = new Default ();
    D.show ();
  }

"Run Results":

Base type initialization value

boolean<----->false

char<----->

byte<----->0

short<----->0

int<----->0

long<----->0

float<----->0.0

double<----->0.0

Where thedefault value of the char type is null (NULL).

For a non-basic data type, the handle of the object is also initialized:

Class Person {
  private String name;
  Setter
}
class Default {person
  p;
  public void Show () {
    System.out.println ("person<----->" + P);
  }
public class InitValue {public
  static void Main (string[] args) {
    default d = new Default ();
    D.show ();
  }

"Run Results":

person<----->null

Visible, the handle initialization value is NULL. This means that if you do not specify an initialization value for p to invoke p.setName a method like this, an exception will occur.

Rule initialization

If you need to assign an initial value to a variable, you can assign a value at the same time as you define the variable.

Class default{
  Boolean t = true;
  char c = ' A ';
  byte B =;
  Short s = 0xff;
  int i =;
  Long L = 999;
  float f = 1.2f;
  Double d = 1.732;
  public void Show () {
    System.out.println (
            "boolean<----->" + t + "\ n" +
            "char<----->" + c + "\ n") +
            "byte<----->" + B + "\ n" +
            "short<----->" + S + "\ n" +
            "int<----->" + i + "\ n" +
            " long<-----> "+ L +" \ n "+
            " float<-----> "+ f +" \ n "+
            " double<-----> "+ D +" \ n "
    );

  }
public
class InitValue {public
  static void Main (string[] args) {
    default d = new default ();
    D.show ();
  }

Even a method can be used to initialize;

class Person {
  int i = set ();
  //...
}

These methods can also use arguments:

class Person {
  int i;
  Int J = Set (i);
  //...
}

Builder initialization

The advantage of the builder initialization is that the initialization value can be determined at run time. For example:

class Person {
  int age;
  Person () {Age
    =;
  }
}

The age is first initialized to 0 and then 89. This is true for all the basic types and the handles of the object.

Order of initialization

In a class, the order of initialization is determined by the order in which the variables are defined within the class. Even if the variable definition is large in the middle of the method definition, the variable will still be initialized before any method (including the constructor) is invoked. For example:

Class Pet {
  pet (int age) {
    System.out.println ("Pet (" + Age +) ");
  }

Class Person {
  Pet T1 = new pet (1);

  Person () {
    System.out.println ('---person ()---");
    T3 = new Pet (a);

  Pet t2 = new Pet (2);
  void Show () {
    System.out.println ("show----Running");
  pet T3 = new pet (3);
}


public class Orderofinitialization {public
  static void Main (string[] args) {person
    p = new Person ();
    P.show ();
  }

"Run Results":

Pet (1)

Pet (2)

Pet (3)

---person ()---

Pet (<br/>)

Show----Running

In the example above, although T1, T2, and T3 are defined throughout the class, but the sequence of initialization is determined by the sequence of definitions of T1, T2, and T3 (swapping T1, T2, T3 to see the results), and initialization takes precedence over builder execution, and T3 reinitialization when the person's builder is invoked.

Initialization of static data

If the data is static (static), the same procedure is executed. If it is of a basic type and is not initialized, it automatically obtains its own standard base type initializer, and if it is a handle to an object, a null value (NULL) is obtained unless an object is created to connect to it. If initialized at definition, the method taken is different from the non-static value because the static has only one storage area. For example,

Class Bowl {Bowl (int marker) {System.out.println ("Bowl (" + marker +) ");
  } void f (int marker) {System.out.println ("f (" + marker +) ");
  The class Table {static Bowl B1 = new Bowl (1);
    Table () {System.out.println ("table ()");
  B2.F (1);
  } void F2 (int marker) {System.out.println ("F2 (" + marker +) ");
static Bowl B2 = new Bowl (2);
  Class Cupboard {Bowl B3 = new Bowl (3);
  static Bowl b4 = new Bowl (4);
    Cupboard () {System.out.println ("cupboard ()");
  B4.F (2);
  } void F3 (int marker) {System.out.println ("F3 (" + marker +) ");
static Bowl B5 = new Bowl (5); public class Staticinitialization {public static void main (string[] args) {System.out.println ("Creating New Cup
    Board () in main ");
    New Cupboard ();
    SYSTEM.OUT.PRINTLN ("Creating new Cupboard () in main");
    New Cupboard ();
    T2.F2 (1);
  T3.F3 (1);
  static Table t2 = new Table ();
static cupboard T3 = new cupboard (); }

"Run Results":

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)

Static code block

Java allows other static initialization work to be divided into a special block of code within the class, in the form of a static keyword followed by a method body, called a static code block. A static code block executes only when the object of that class is first generated or when a static member belonging to that class is first accessed. For example:

Class Person {person
  (int age) {
    System.out.println ("person (+ Age +)");
  }
  void f (int age) {
    System.out.println ("f (" + Age +) ");
  }

Class Persons {
  static person P1;
  static person P2;
  static {
    P1 = new person (1);
    P2 = new Person (2);
  }
  Persons () {
    System.out.println ("Persons ()");
  }
}

public class Explicitstatic {public
  static void Main (string[] args) {
    System.out.println ("Inside Main ()"); C22/>PERSONS.P1.F (%);//1
  }
  static Persons x = new Persons ();//2
  static Persons y = new Persons ();//2
   }

The static initialization module for persons runs when access to the static object P1 in a row marked 1, or when row 1 is commented and Line 2 is not commented. If both 1 and 2 are commented out, the static block of code used for persons is not executed.

Sequence of execution of static properties and static code blocks

Class Person {person
  (int age) {
    System.out.println (' Person (' +age+ ') ');
  }
Class Persons {
  static person p = new person (2);//1
  static {
    p = new person (3);
  }
  static person p = new person (2);  2

} public
class Compstaticinit {public
  static void Main (string[] args) {

  }
  static Persons x = new Persons ();
}

According to note 1, 2, note 2 retention 1 results analysis that static properties and static code block execution order depends on the order of the encoding. Who executes first in front.

Initialization of non-static Properties

Class Animal {
  Animal (int age) {
    System.out.println ("Animal (" + Age +) ");
  }
  void f (int age) {
    System.out.println ("f (" + Age +) ");
  }
public class Notstaticinit {
  Animal A1;
  Animal A2;
  {
    A1 = new Animal (1);
    A2 = new Animal (2);
    System.out.println ("A1 & A2 initialized");
  }
  Notstaticinit () {
    System.out.println ("Notstaticinit");
  }
  public static void Main (string[] args) {
    System.out.println ("Inside Main ()");
    Notstaticinit x = new Notstaticinit ();
  }
}

Similar to static code blocks, the order in which anonymous and Non-static properties are initialized depends on the encoding order .

Object initialization process in inheritance

Class Insect {
  int i = 1;
  Int J;

  Insect () {
    prt ("i =" + i + ", j =" + j);
    j = 2;
  }

  static int x1 = PRT ("Static insect.x1 initialized");

  static int prt (String s) {
    System.out.println (s);
    return 3;
  }
}

public class Beetle extends insect {
  int k = PRT ("beeklt.k initialized");

  Beetle () {
    prt ("k =" + K);
    PRT ("j =" + j);
  }

  static int x2 = PRT ("Static bootle.x2 initialized");
  static int prt (String s) {
    System.out.println (s);
    return 4;
  }

  public static void Main (string[] args) {
    prt ("Beetle constructor");
    Beetle B = New Beetle ();
  }

"Run Results":

Static insect.x1 initialized

Static bootle.x2 initialized

Beetle constructor

i = 1, j = 0

BEEKLT.K initialized

K = 4

j = 2

When running Java on Beetle, the first thing that happens is that the loader finds that class outside. During the load process, the loader discovers a base class, so it is loaded with it. This procedure executes regardless of whether the object of the underlying class is generated. If the underlying class contains another underlying class, then another base class is loaded, and so on. It then executes static initialization in the root base class, executes in the next derived class, and so on. This is because the initialization of the derived class may depend on initialization of the underlying class member.

When the class is loaded, the object can be created. First, all of the base data types in this object are set to their default values, and the object handle is set to NULL. The builder of the underlying class is then executed. This is done automatically (either by default in the constructor of the derived class super(), or by super specifying the base class's builder). When the base class Builder completes, the derived class instance variables are initialized in their original order, and then the remaining body parts of the builder are executed.

To summarize the process of creating an object:

Static is performed only once when the class is loaded and only once;

Non-static is performed only when instantiated, each time the object is created;

Static is executed before non-static, the base class static takes precedence over the derivative class static execution;

The execution properties of static properties and static blocks of code depend on their position in the class, and who executes first;

The order in which non-static properties and building blocks are executed depends on their location in the class and who executes them before.

Summarize

Through the above, we have an understanding of how to initialize the objects in Java and how to execute the initialization code, as well as the circumstances in which we might use uninitialized variables. Once you have a detailed understanding of these issues, you can circumvent some of the risks in coding to ensure that an object is completely initialized before it is visible.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.