From http://www.cnblogs.com/ggjucheng/archive/2012/11/28/2793158.html
Object
A typical JavaProgramAs you know, many objects are created to interact with each other through method calls. Through object interaction, a program can complete many tasks, such as running an animation on the GUI and sending or receiving information over the network. When a created object completes a task, its resources will be reused by other objects.
There is a small program calledCreateobjectdemo
It creates three objects: One Point Object and twoRectangle
Object. To compile this program, we need three source code files.
Public Class Createobjectdemo { Public Static Void Main (string [] ARGs ){ // Declare and create a Point Object // And two rectangle objects. Point originone = New Point (23, 94 ); Rectangle rectone = New Rectangle (originone, 100,200 ); Rectangle recttwo = New Rectangle (50,100 ); // Display rectone's width, // Height, and area System. Out. println ("width of rectone:" + Rectone. width); system. Out. println ( "Height of rectone:" + Rectone. Height); system. Out. println ( "Area of rectone:" + Rectone. getarea ()); // Set recttwo's position Recttwo. Origin = Originone; // Display recttwo's position System. Out. println ("X position of recttwo:" + Recttwo. Origin. X); system. Out. println ( "Y position of recttwo:" + Recttwo. Origin. y ); // Move recttwo and display // Its new position Recttwo. Move (40, 72 ); System. Out. println ( "X position of recttwo:" + Recttwo. Origin. X); system. Out. println ( "Y position of recttwo:" + Recttwo. Origin. Y );}}
This program creates an object, controls the object, and displays the information of multiple objects. Here is the output:
Width of rectone: 100Height of rectone:200Area of rectone:20000X position of recttwo:23Y position of recttwo:94X position of recttwo:40Y position of recttwo:72
The following example describes the lifecycle of an object in a program. You will learn how to writeCodeCreate and use objects in your own programs. You will also understand that when the object lifecycle ends, the system will clear the object.
Create object
As you know, a class provides a blueprint for an object. You can use the class to create an object.Createobjectdemo
Every statement in the program creates an object and assigns it to the variable:
Point originone =NewPoint (23, 94); Rectangle rectone=NewRectangle (originone, 100,200); Rectangle recttwo=NewRectangle (50,100 );
The object of the pointer class is created in the first row, and the object of the second row and the third row are created respectively.Rectangle
Class Object. Each statement has three parts (details are as follows ):
1. Declaration: Data Type and variable name
2. instantiation: The New Keyword is the Java operator used to create objects.
3. Initialization: the new operator is followed by a constructor to initialize the object.
Declare a variable pointing to an object
Previously, we learned that declaring a variable will write like this:
Type name;
This notifies the compiler that you will use name to point to data of type. If it is a native type variable, this declaration will allocate a suitable size of memory for the variable.
You can also declare a reference variable in a single row, for example:
Point originone;
If originone is declared in this way, its value is uncertain before creating an object and assigning it to it. Declaring a referenced variable does not create an object. To create an object, you must use the new operator. We must useOriginone
You must assign an object to it. Otherwise, the compiler reports an error.
If a variable does not point to any object, you can explain it as follows (variable name, originone, add a reference that does not point to other objects ):
Instantiate a class
The new operator instantiates class objects, allocates memory, and returns memory references. The new operator also calls the class constructor.
Note: instantiating a class means creating an object. When you create an object, you create an instance of a class. This is to instantiate a class.
The new operator requires an independent parameter with a suffix: A constructor call. The constructor name provides the instantiation of the corresponding class.
The new operator returns the reference of the created object. This reference is used to assign values to suitable types of variables. For example:
Point originone =NewPoint (23, 94 );
The reference returned by the new operator may not have to be assigned to a variable. It can also be used directly in the expression. For example:
IntHeight =NewRectangle (). height;
Initialization object
Here is the point class code:
Public ClassPoint {Public IntX = 0;Public IntY = 0;//ConstructorPublicPoint (IntA,IntB) {x=A; y=B ;}}
This class has only one constructor. You can see that it is a constructor, because its Declaration uses the same name as the class name and has no return value. The Point class constructor has two Integer Parameters, just like the code declaration.(Int A, int B ). The following statements use 23 and 94 as the parameter values:
Point originone =NewPoint (23, 94 );
The statement execution result can be described as follows:
Here isRectangle classIt has four constructor methods:
Public Class Rectangle { Public Int Width = 0 ; Public Int Height = 0 ; Public Point origin; // Four Constructors Public Rectangle () {Origin = New Point (0, 0 );} Public Rectangle (point P) {Origin = P ;} Public Rectangle ( Int W, Int H) {Origin = New Point (0, 0 ); Width = W; Height = H ;} Public Rectangle (point P, Int W, Int H) {Origin = P; Width = W; Height = H ;} // A Method for moving the rectangle Public Void Move ( Int X, Int Y) {origin. x = X; origin. Y = Y ;} // A method for computing the area // Of the rectangle Public Int Getarea (){ Return Width * Height ;}}
Each constructor provides you with the initial values of the length and width of the rectangle. The parameters are for both the native type and the reference type. If a class has many constructor methods, they must have different signatures. The Java compiler uses different constructor methods based on the number and type of parameters. When the Java compiler encounters the following code, it knows to call the constructor of the pointer class with the parameter pointer followed by two integers:
Rectangle rectone =NewRectangle (originones, 100,200 );
Call this constructor and initialize rectoneOriginone
. Similarly, the constructor sets the width to 100 and the height to 200. Now there are two references pointing to the samePoint Object-an object can be pointed to by multiple references, as shown in the following figure:
The following code callsThe rectangle class parameter is a constructor of Two integer types. It providesWidth andThe initialization value of height. If you check the constructor code, you will seePoint Object. Attribute X and Y are initialized to 0:
Rectangle recttwo =NewRectangle (50,100 );
In the following statement, the rectanglez constructor does not have any parameters. It is called the non-argument constructor:
Rectangle rect =NewRectangle ();
All classes have at least one constructor. If the class does not explicitly declare a constructor, the Java compiler automatically provides a constructor called the default constructor. The default constructor calls the non-argument constructor of the parent class. If the parent class does not have a constructor method (the object class has a constructor), the compiler rejects this program.
Objects used
When you create an object, you are very likely to use it to do something. You may use its member variable value to change its member variable value, or call its method to complete a task.
Reference object member variables
Object member variables are accessed by name. You must use a clear name.
You can use a simple name in the class. For example, we canRectangle
Class to add a statement, output length and height:
System. Out. println ("width and height are:" + width + "," + height );
In this scenario,Width
AndHeight is a simple name.
In code, access outside the class must use a class reference or expression, with A. operator and a simple member variable name. For example:
Objectreference. fieldname
Example,The createobjectdemo class code is inThe outer layer of the rectangle, so the object name to be referenced isRectoneOfOrigin,Width, AndHeightThese member variables,CreateobjectdemoClasses must be used separatelyRectone. Origin,Rectone. Width,Rectone. Height. This program uses the following name to displayRectoneWidth and height of the object:
System. Out. println ("width of rectone:" +Rectone. width); system. Out. println ("Height of rectone:" + rectone. Height );
The code in the createobjectdemo class tries to use a simple nameWidthAndHeightIs meaningless-These member variables only have corresponding objects, which leads to a compilation error.
Wait until this program uses the same code to displayRecttwo. Multiple objects of the same type have their own member variables. So everyAll rectangle objects have their own member variables.Origin,Width,Height. When you access the instance's member variables through object reference, you reference the member variables of the corresponding object. Two objectsRectoneAndRecttwoThe createobjectdemo program has its ownOrigin,Width,Height member variable.
To access member variables, you can use the command reference of an object, just like in the previous example, or use an expression to return an object reference. Call the new operator again to return an object reference. In retrospect, the new operator returns an object reference. So you can access the member variable of the object by the value returned by new:
IntHeight =NewRectangle (). height;
This statement is createdRectangle object and understand how to get its height. In essence, this statement obtainsRectangleThe default height of the program. However, after the statement is executed, no reference of the program directs to the createdRectangleObject. Because the program does not store the reference. The object is not referenced, and its resources are recycled by the Java Virtual Machine.
Method of calling object
You can call the object method through object reference. You add a. operator to the object reference, and then append the concise name of the method. Of course, you need to provide method parameters in Closed parentheses. If the method does not require any parameters, use empty parentheses.
Objectreference. methodname (argumentlist); or: objectreference. methodname ();
The rectangle class has two methods:Getarea () calculates the rectangular area,Move () modify the rectangle size,CreateobjectdemoThe Code calls the following two methods:
System. Out. println ("area of rectone:" +Rectone. getarea ();... recttwo. Move (40, 72 );
The first statement is called.RectoneOfGetarea () method and display the result. Second statement AdjustmentRecttwo size,The move () method returnsOrigin. xAndOrigin. YNew value.
Like the instance member variable, objectreference must be an object reference. You can use a variable name, but you can also use any expression that returns an object reference. The new operator returns an object reference, so that you can use the new return value to call the method of the new object:
NewRectangle (100, 50). getarea ()
ExpressionNew rectangle (100, 50)Returns an object reference pointingRectangle object.You can use the. symbol to call the getarea () method of the new rectangle to calculate the area of the newly created rectangle.
Some methods, suchGetarea (), Returns a value. For the return value of a method, you can use a method call in an expression to assign the return value to a variable and use it for conditional judgment and loop control. The following codeGetarea ()The return value is assigned to the variable areaofrectangle:
IntAreaofrectangle =NewRectangle (100, 50). getarea ();
Remember, calling a method for an object is like sending a message to an object. In this scenario,The rectangle object returned by the constructor references and callsGetarea ()
Garbage Collector
Some object-oriented languages require you to track all created objects. When they are not needed, you need to explicitly destroy them. Displaying and managing memory is cumbersome and error-prone. the Java platform allows you to create as many objects as possible (a limited number of objects are determined by the processing capability of your system ), you don't have to worry about when to destroy objects. This process is called garbage collection.
When the object does not have any reference, it will meet the Garbage Collector's recycle object. References are generally stored in variables. When a variable leaves the block range, it is destroyed. Of course, you can also set a variable to null to explicitly delete an object reference. Note how many references can be referenced to an object in the program. If all references are deleted, this object is consistent with the collection object of the garbage collector.
Java Runtime Environment has a garbage collector that periodically releases the memory of objects that are no longer referenced. The garbage collector runs automatically and determines the correct running time.