Java 4 Android class and object initialization

Source: Internet
Author: User

Java 4 Android class and object initialization
1. Member Initialization

Java tries its best to ensure that all variables can be properly initialized before use.

1) local variables of the method. Java implements this guarantee by compiling errors. Eg:

void f(){    int i;    i++; //Error , i not initialized}
2) data member of the class. If it is a basic type, they all have an initial value. If it is an object reference, the reference will be initialized to null.

Specify Initialization

What should I do if I want to assign a value to a variable?

1) assign values directly to the class member variables (Note: C ++ is not allowed, although C ++ Beginners always want to do this)

class Depth{}public class InitialValues{    boolean bool = true;    char ch = 'x';    int i = 999;    Depth d = new Depth();}
2) call a method to provide the initial value.

public class MethodInit{int i = f();int f(){return 11;}}
This function can also contain parameters, but must be initialized.

public class MethodInit2{int i = f();int j = g(i);int f(){    return 11;}int g(int n){   return n*10;}}
However, the following statements are indeed incorrect.

public class MethodInit3{// int j = g(i) ; //Illegal forward referenceint i = f();int f(){return 11;}int g(int n){return n*10;}}
Obviously, the correctness of the above procedures depends on Initialization order. The compiler sends a warning "Forward reference.

The above Initialization is simple and quick in the definition, so that each created object has the same value.

2. constructor Initialization

In C ++, it is called a constructor. It is a thing. The automatic initialization mentioned in the previous section will be executed and will be executed before the constructor.

public class Counter{int i;Counter(){i = 8;}}
In the above code, I is first set to 0 and then changed to 7.

The initialization sequence is within the class, and the variable definition sequence determines the initialization sequence. Even if the variable definitions are scattered between the method definitions, they are still initialized before any methods (including constructors) are called.
class Window{Window(int marker){print("window("+marker+")");}}class House{window w1 = new Window(1);House(){print("house()");w3 = new Window(33);}Window w2 = new Window(2);void f(){print("f()");}Window w3 = new Window(3);}public class OrderOfInitialization{public static void main(String[] args){    House h = new House();   h.f();}}/**Output**//*Window(1)Window(2)Window(3)House()Window(33)f()*/
Static Data Initialization
class Bowl{Bowl(int marker){print("Bowl("+marker+")");}void f1(int marker){print("f1("+marker+")");}}class Table{static Bowl bowl1 = new Bowl(1);Table(){    print("Table()");    bowl2.f1(1);}void f2(int marker){    print("f2("+marker+")");}static Bowl bowl2 = new Bowl(2);}class Cupboard{Bowl bowl3 = new Bowl(3);static Bowl bowl4 = new Bowl(4);Cupboard(){    print("Cupboard()");    bowl4.f1(2);}void f3(int marker){    print("f3("+marker+")");}static Bowl bowl5 = new Bowl(5);}public class StaticInitialization{public static void main(String[] args){print("Creating new Cupboard() in main");new Cupboard();print("Creating new Cupboard() in main");new Cupboard();table.f2(1);cupboard.f3(1);}static Table table = new Table();static Cupboard cupboard = new Cupboard();}/**output*//*Bowl(1)Bowl(2)Table()f1(1)Bowl(4)Bowl(5)Bowl(3)Cupboard()f1(2)Creating new Cupboard in mainBowl(3)Cupboard()f1(2)Creating new Cupboard in mainBowl(3)Cupboard()f1(2)f2(1)f3(1)*/
Please carefully read the above Code and results. It is better to run it on your own. The initialization sequence is static objects first and then non-static objects. Static Initialization is only performed when necessary. If you do not create a Table object or reference Table. b1, Table. b2, static Bowl b1 and b2 will never be created. The following steps explain why. The object creation process is summarized. Suppose there is a class named Dog: 1) even if the static keyword is not explicitly used, the constructor is actually a static method. Therefore, when a Dog-type object is created for the first time (the constructor can be regarded as a static method) or a static method of the Dog class, when the static domain is accessed for the first time, the Java interpreter must find the path to locate the Dog. class file. 2) Load Dog. class (this creates a Class Object), and all static initialization actions will be executed. Therefore, static Initialization is only performed once when the Class object is loaded for the first time. 3) when using new Dog () to create an object, sufficient storage space will be allocated to the Dog object on the heap. 4) This bucket will be cleared. This automatically sets all the basic data types in the Dog object to the default value, and the reference is set to null. (Re-emphasize that local variables inside the method will not be initialized. If uninitialized local variables are used, a compilation error will be prompted ). 5) execute all initialization actions that appear in the field definition. 6) execute the constructor.
Explicit static initialization (static block) Java allows multiple static initialization actions to be organized into a special "static clause" (also called static block ).
public class Spoon{static int i;static {    i = 47;}}
The above code is the same as static initialization, and the code is only executed once when necessary.
class Cup{Cup(int marker){    print("Cup("+marker+")");}void f(int marker){    print("f("+marker+")");}}class Cups{static Cup cup1;static Cup cup2;static {    cup1 = new Cup(1);    cup2 = new Cup(2);}Cups(){    print("Cups()");}}public class ExplicitStatic{    public static void main(String[] args){     print("Inside main()");     Cups.cup1.f(99);//(1)}    //static Cups cups1 = new Cups();//(2)    //static Cups cups2 = new Cups();//(3)}/**output*//*Inside main()Cup(1)Cup(2)f(99)*/
Whether the above Code is run (1) or (1) Annotated run (2), the static initialization of Cups will be executed. (3) You can also open it and check it. It doesn't matter because the static Initialization is only performed once.
The non-static instance initializes it after static initialization. Before the constructor, we described this step. Let's look at a piece of code:
class Mug{Mug(int marker){    print("Mug("+marker+")");}void f(int marker){    print("f("+marker+")");}}public class Mugs{Mug mug1;Mug mug2;{    mug1 = new Mug(1);    mug2 = new Mug(2);    printf("mug1 & mug2 initialized");}Mugs(){    print("Mugs()");}Mugs(int i){    print("Mugs(int)");}public static void main(String[],args){    print("Inside main()");    new Mugs();    print("new Mugs() completed");    new Mugs(1);    print("new Mugs(1) completed");}}/** output*//*Inside main()Mug(1)Mug(2)mug1 & mug2 initializedMugs()new Mugs() completedMug(1)Mug(2)mug1 & mug2 initializedMugs(int)new Mugs(1) completed*/

This syntax is required to support the initialization of "anonymous internal classes. Tired. I learned it here today.









Related Article

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.