Java (Classes and objects)

Source: Internet
Author: User

1> Object Award, etc.

Please enter and run the following code to get what results?

1  Public classTest {2 3      Public Static voidMain (string[] args) {4         //TODO auto-generated Method Stub5Foo obj1 =NewFoo ();6Foo Obj2 =NewFoo ();7System.out.println (obj1 = =obj2);8     }9 }Ten classfoo{ One     intValue = 100; A}

Results:

Analysis:

1) when "= =" is applied to the original data type variable, is the data saved by the comparison variable equal

2) when "= =" is applied to a reference type variable, it is compared whether the two variables refer to the same object.

3) The reference represents the address, so "= =" is actually equivalent to comparing the address of an object saved in a two reference type variable. Two objects each have their own addresses, so the result is false.

2> initialization block for class

If a class has both an initialization block and a constructor, and it also sets the initial value of the field, who decides?

1  Public classTest2 {2 3      Public Static voidMain (string[] args) {4         5Initializeblockclass obj=NewInitializeblockclass ();6 System.out.println (Obj.field);7         8obj=NewInitializeblockclass (300);9 System.out.println (Obj.field);Ten     } One  A } - classinitializeblockclass{ -     //The following sentence affects the initial value of the Field field before and after the initialization block the     //public int field=100; -      -     { -field=200; +     } -      Public intfield=100; +      PublicInitializeblockclass (intvalue) { A          This. field=value; at     } -      PublicInitializeblockclass () { -          -     } -}

Results: if {field=200;} Prior to filed=100 :

if {field=200;} Prior to filed=100 :

Analysis: Executes the initialization block of the specified default value or class when the class member definition is executed, preceded by first execution. You can also assign a value to a class by executing its constructor.

3> execution order of static initialization blocks

Run the teststaticinitializeblock.java sample, observe the output, and summarize the "Order of execution of static initialization blocks".

1 classRoot2 {3     Static{4SYSTEM.OUT.PRINTLN ("Static initialization block of root");5     }6     {7System.out.println ("Root's normal initialization block");8     }9      PublicRoot ()Ten     { OneSYSTEM.OUT.PRINTLN ("Root parameter-free constructor"); A     } - } - classMidextendsRoot the { -     Static{ -SYSTEM.OUT.PRINTLN ("Static initialization block for mid"); -     } +     { -SYSTEM.OUT.PRINTLN ("Normal initialization block for mid"); +     } A      PublicMid () at     { -SYSTEM.OUT.PRINTLN ("parameter-free constructor for mid"); -     } -      PublicMid (String msg) -     { -         //calling overloaded constructors in the same class through this in          This(); -System.out.println ("Mid with parametric constructor, its parameter value:" +msg); to     } + } - classLeafextendsMid the { *     Static{ $SYSTEM.OUT.PRINTLN ("Static initialization block of the leaf");Panax Notoginseng     } -     { theSYSTEM.OUT.PRINTLN ("Plain initialization block of the leaf"); +     }     A      PublicLeaf () the     { +         //A constructor that invokes a string argument in the parent class through Super -         Super("Java Initialization sequence Demo"); $System.out.println ("The constructor that executes the leaf"); $     } - } -  the  Public classTeststaticinitializeblock - {Wuyi      Public Static voidMain (string[] args) the     { -         NewLeaf ();  Wu     } -}

Results:

Analysis: static initialization blocks are executed only once. When you create an object of a subtype, it also causes the execution of the static initialization block of the parent type. static initialization blocks are executed during the class initialization phase, rather than when the object is created. so static initialization blocks are always executed first than normal initialization blocks. Executes the static initialization block in the Java.lang.Object class first, then executes the static initialization block of its parent class, and finally executes the static initialization block of the class. After this process, the initialization of the class is completed. This class can be used in the system only if the class initialization is complete, or the class is used to create instances. all static initialization blocks are executed first, then execute the normal initialization block of the class, finally executes the constructor of the class.

4> static methods for classes

Static methods only allow access to static data, so how do you access the instance members of a class in a static method (that is, a field or method that does not have the static keyword attached)?

 Public classtext3{intx = 3;//the instance variable of the class, initialized with a value of 3 Static inty = 4;//A static variable of class, initialized with a value of 4  Public Static voidMethod ()//Static Methods{System.out.println ("Instance variable x =" +NewTEXT3 (). x);//accessing an instance variable of a class in a static method requires first instantiating the classSYSTEM.OUT.PRINTLN ("static variable y =" + y);//Static variables of a class can be accessed directly in a static method  }  Public Static voidMain (string[] args) {Text3.method (); TEXT3 ex=NewText3 (); System.out.println ("x =" +ex.x); System.out.println ("y =" +ex.y); }}

Results:

Analysis:Accessing an instance variable of a class in a static method first requires the instantiation of the class.A static method or property in a class is not a member of that class in nature ,Javawhen a virtual machine is loaded into a class, these static things already have objects, which are only in this class"Aliens", you do not need to instantiate through the class's constructor (constructor) class, rather than a static property or method, where the class's load does not exist, and you need to rely on the instance object of the class to exist after executing the class's constructor. When you call a static method externally, you can use the"class name.Method Name"the way, you can also use"Object Name.Method Name"the way. The instance method is only in the following way. That is, calling a static method eliminates the need to create an object. When a static method accesses members of this class, it only allows access to static members (that is, static member variables and static methods), not to instance member variables and instance methods, and the instance method does not.

6> using static fields and constructors for classes

using the class's static fields and constructors, we can track the number of objects created by a class. Write a class that can query it at any time "how many objects have you created?" ”。

//write a class that can query it at any time "how many objects have you created?" " Public classTest4 { Public Static voidMain (string[] args) {//TODO auto-generated Method StubObjectnumber obj1 =NewObjectnumber (); Objectnumber Obj2=NewObjectnumber (); }}classobjectnumber{Private Static intNumber ;  PublicObjectnumber () { number++; System.out.printf ("You have created%d objects", number); System.out.print ("\ n"); }}               

Results:

Analysis: writes the counter in the constructor, each time an object is generated, a constructor is called, and the Count number is set to a static class to ensure that the next call does not change the last value.

Java (Classes and objects)

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.