Java object-oriented object/reference

Source: Internet
Author: User
Tags class definition

This page was updated on July 17, 2016

Object/reference

In the preceding Persontest.java code, there is a line of code: Person p = new person ();
This line of code creates a person instance, also known as the Person object, which is assigned to the P variable.

This line of code actually produces two things: one is the P variable, and the other is the person object.

From the person class definition, the person object should contain two instance variables, and the variables need memory to store them.
Therefore, when you create a person object, you have the corresponding memory to store the instance variables of the person object.
Let's draw a picture for you. (The person object is stored in memory)

As you can see, the person object consists of multiple pieces of memory, each of which stores different member variables of the person object.
When you copy this person object to a reference variable, how does the system handle it?
Is the system going to copy this person object in memory again? Of course not, Java is not so stupid.
Java lets reference variables point to this object.
In other words, the reference variable holds only a reference, which points to the actual object.

Similar to the array type described earlier, a class is also a reference data type.
So a variable of the person type defined in the program is actually a reference, which is stored in the stack memory and points to the actual person object.
The real person object is stored in the heap memory.
And then I'll show you a picture showing the person object assigned to a reference variable.

The reference variable in the stack memory does not really store the object's member variables.
The member variable data for the object is actually stored in the heap memory.
The reference variable simply points to the object in the heap's memory.

When an object is created, the object is saved in heap memory.
Java programs do not allow direct access to objects in heap memory
The object can only be manipulated through a reference to the object.
That is, arrays and objects can only be accessed by reference, regardless of their time.

Objects in the heap memory can have multiple references.
That is, multiple reference variables can point to the same object. For example, the following code:

//将 p 变量的值赋给 p2 变量Person p2 = p;

The above line of code assigns the value of the P variable to the P2 variable.
That is, assign the address saved by the P variable to the P2 variable.
This way the P2 variable and the p variable will point to the same person object in the heap memory. You understand?
This way, regardless of the member variables and methods that access the P2 variable, the member variables and methods of the P variable are accessed.
When they actually access the member variables and methods of the same person object, the same access results are returned.

Tip: If the object in the heap memory does not have any variables pointing to the object, then the program will not be able to access the object and the object will become garbage, and the Java garbage collection mechanism will recycle the object.
And frees up the memory it occupies.

Therefore, if you want an object to be recycled, you just need to cut off all reference variables and relationships between the objects. That is, the value of these reference variables is assigned to: null

The This reference of the object

Java provides a the This keyword, which always points to the object that called the method.
This is the default reference for an object in two scenarios, depending on where this occurs.

    • The object that the constructor is initializing is referenced in the constructor.
    • The object that invokes the method is referenced in the method.

The most important role of the This keyword is to allow one method in the class to access another method or instance variable in the class.
We assume that a dog class is defined, and the run () method of the dog object needs to call its jump () method.
So what should we do?
Should you do this?

publicclass Dog{    //定义 jump() 方法    publicvoidjump()    {        System.out.println("狗狗要跳跳");    }    //定义 run() 方法, run() 方法需要借助 jump()方法    publicvoidrun()    {        new Dog();        d.jump();        System.out.println("狗狗跑啊跑");    }}

Using this method to define the Dog class, it is true that the jump () method can be called in the Run () method.
The following provides a program to create a Dog object and invoke the run () method of the object

publicclass DogTest{    publicstaticvoidmain(String[] args)    {        //创建Dog对象        new Dog();        //调用Dog对象的 run() 方法        dog.run();    }}

In the above program, two Dog objects were produced altogether.
In the Run () method of the dog class, the program creates a dog object.
And make a reference variable named D to point to the Dog object.

In the main () method of Dogtest, the program creates a Dog object again.
And make a reference variable named dog to point to the dog object.

Here are two questions:

    • Does calling the jump () method in the run () method necessarily require a Dog object?
    • Do you necessarily need to recreate a Dog object?

The answer to the first question is yes, because member variables and methods that do not use static adornments must be called using objects.
The answer to the second question is a negative one. Because when the program calls the run () method, it is guaranteed to provide a Dog object.
This makes it possible to use the existing dog object directly, without recreating the dog object.

Therefore, the object that calls the method needs to be obtained in the run () method, which can be satisfied by the This keyword.
This can represent any object, and when this appears in a method body, the object it represents is indeterminate.
But its type is deterministic, and the object it represents can only be the current class.
Only if this method is called is the object it represents is determined.
Who is calling this method, this is on behalf of WHO.

Therefore, it is more appropriate to change the run () method of the previous Dog class to the following form:

//定义一个 run() 方法, run() 方法需要借助 jump() 方法publicvoidrun(){    //使用 this 引用调用run() 方法的对象    this.jump();    System.out.println("狗狗跑啊跑");}   

The code above is better, and when a Dog object calls the Run () method, the run () method needs to rely on its own jump () method.

In reality, the case where one method of an object relies on another method is common:

    • The method of eating depends on the method of taking chopsticks
    • The writing procedure method relies on the knocking keyboard method

This dependency is a dependency between two methods of the same object.
Therefore, Java allows one member of an object to invoke another member directly. This prefix can be omitted.
In other words, changing the run () method above to the following form is completely correct.

publicvoidrun(){    jump();    System.out.println("狗狗跑啊跑");}

Most of the time, a method that accesses other method/member variables defined in the class has the same effect without the this prefix.

For static decorated methods, you can use a class to call the method directly.
If you use the This keyword in a static decorated method, the keyword cannot point to the appropriate object.
Therefore, the This reference cannot be used in static decorated methods.
The static decorated method cannot use the this reference, so the static decorated method cannot access ordinary members that do not use the static adornment.
Therefore, the Java syntax stipulates that static members cannot access non-static members directly.

Write a code below to demonstrate this error usage:

public  class  staticaccessnonstatic  {  public  void      Info  () {System.out.println ( "simple Info method" ); } public  static   void  main  (string[] args) {//because the main () method is a static method , and info () is a non-static method  //calling the main () method is the class itself, not an instance of the class  //So omitted this cannot point to a valid object (you add this also does not)  info (); }}

The above error because the info () method is a method that belongs to the instance. Instead of the method that belongs to the class.
Therefore, you must use an object to invoke the method.
When you call the info () method directly in the main () method above, the system is equivalent to using this as the caller of the method.
The main () method is a static modified method, and the static modified method belongs to the class, not to the object.
So the call to the static decorated method is always the class itself.
If the this reference is allowed in a static decorated method, it will cause this to not reference a valid object, so the above program has a compilation error.
If you confuse this concept, the simplest solution is that you write the program later, the static modifier members you use the class to invoke, do not use the instance to invoke. Can you understand?

If you do need to access a non-static method in a static method.
You can only recreate one object.
For example, the info () call above is changed to the following form:

new StaticAccessNonStatic().info();

Most of the time, the normal method does not need to use this prefix to access other method/member variables.
But if there is a local variable and a member variable name in the method
The program also needs to access the overridden member variable in the method, and the this prefix must be used.
The knowledge about local variables overriding member variables will later be said.

In addition, this reference can also be used as the default reference in the constructor.
Because the constructor is called directly using the New keyword, instead of using the object.
So this represents the object that the constructor is initializing in the constructor.

 Public  class thisinconstructor{    //Define a member variable named Foo     Public intFoo Public Thisinconstructor()    {//define a Foo variable in the constructor        intFoo =0;//Use this to represent the object that the constructor is initializing        //The following code will set the Foo member variable of the object that the constructor is initializing to 6         This. Foo =6; } Public Static void Main(string[] args) {//Foo member variable for all objects created using Thisinconstructor        //will be set to 6, so the code below will output 6System.out.println (NewThisinconstructor (). foo); }}

When this reference is used in the Thisinconstructor constructor, this always references the object that the constructor is initializing.
This.foo = 6 This statement sets the Foo member variable of the Thisinconstructor object that is executing the initialization to 6.
This means that the Foo member variable of all objects returned by the constructor equals 6

Similar to normal methods, the this prefix can be omitted most of the time when accessing other member variables and methods in the constructor.
However, if the constructor has a local variable with the same name as the member variable and must access the overridden member variable in the constructor, the this prefix must be used.

When this is used as the default reference for an object, the program can access the this reference as if it were a normal reference variable.
This can even be used as the return value of a normal method.
Write a program to see

 Public  class returnthis{     Public intAge PublicReturnthisGrow() {age++;//return This returns the object that called the method        return  This; } Public Static void Main(string[] args) {Returnthis RT =NewReturnthis ();//Can call the same method continuouslyRt.grow (). Grow (). grow (); System.out.println ("The value of the age member variable for RT is:"+ rt.age); }}

As you can see from the program above, if you use this as the return value in a method. You can call the same method multiple times in a row.
This makes the code more concise.
However, this method of using this as the return value may cause a blur of practical significance, such as the Grow method above, which represents the growth of an object, that is, the value of the age member variable plus 1. There should actually be no return value.

Java object-oriented object/reference

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.