How to use this and super keywords in Java

How to use this and super keywords in Java

I've seen that this and super are used in class inheritance these days. Here's a summary. I'll communicate with you. Please correct any mistakes~

this

This is an object of itself, representing the object itself. It can be understood as a pointer to the object itself.

The usage of this can be roughly divided into three types in Java:

1. Common direct reference

Needless to say, this is equivalent to pointing to the current object itself.

2. The formal parameter has the same name as the member name, which is distinguished by this:

Operation results:

As you can see, age here is the formal parameter of the getage member method, this Age is a member variable of the person class.

3. Reference constructor

Put this together with super, see below.

super

Super can be understood as a pointer to its own super (parent) class object, and this super class refers to the nearest parent class.

Super can also be used in three ways:

1. Common direct reference

Similar to this, super is equivalent to pointing to the parent class of the current object, so you can use super XXX to reference members of the parent class.

2. The member variable or method in the subclass has the same name as the member variable or method in the parent class

Operation results:

You can see that both the methods of the parent class and the variables of the parent class are called here. If the parent class method value () is not called, and only the parent class variable name is called, the parent class name value is null by default.

3. Reference constructor

Super (parameter): call a constructor in the parent class (should be the first statement in the constructor).

This (parameter): call another form of constructor in this class (should be the first statement in the constructor).

Operation results:

It can be seen from this example that super and this can be used to call the constructor of the parent class and other constructors in this class respectively.

In the example, the third construction method of Chinese class calls the second construction method of this class, and the second construction method calls the parent class. Therefore, it is also necessary to call the construction method of the parent class first, then call the second construction method of this class, and finally rewrite the third construction method.

Similarities and differences between super and this:

If you have any questions, please leave a message or go to the community of this site for exchange and discussion. Thank you for reading. I hope it can help you. Thank you for your support to this site!

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>