Two special variables in Java this and super

xiaoxiao2021-03-06  22

Two special variables in Java This and Super2001-04-26 · · Wayne ·· Yesky have two very special variables in Java: this and super, these two variables do not need to be declared before use. The THIS variable is used inside the member function, pointing to the current object, the current object refers to the object that calls the current executing method. The Super variable is directed to the constructor of the superclass, which is used to reference variables and methods in the superclass. So they are all very useful variables, below I want to introduce this and super use method. 1, this piece of code let's look at it: class PersonInformation {String name, gender, nationality, address; int age; void PersonInformation (String p_name, String p_gender, String p_nationality, String p_address, int p_age) {name = p_name; gender = p_gender; national = p_nationality; address = p_address; agent = p_age;}} You will find that the method of this object in the personification () function prompts you to directly access the member variable of the object, and in the same range, define two The local variable of the same name is not allowed. If you really want to make the parameter or method of the class or method of the class or method you define your own partial variable, you need to think that a way to make the member variables and the same name of the same name or Local variables are distinguished, this is to use the THIS variable. Below I want to rewrite the above code, so that each parameter of the constructor of the PersonInformation class has the same name as the object member variable, and the initial value of the member variable is given by the parameters. class PersonInformation {String name, gender, nationality, address; int age; void PersonInformation (String name, String gender, String nationality, String address, int age) {this.name = name; this.gender = gender; this.nationality = Nationality; this.address = address; this.age = age;}} From the previous example, we can see that this constructor must use this, this THIS is used by the method body weight to point to the object instance that is currently executing. The THIS variable is always for classes including the pre-execution method, in the above example, we have to distinguish parameters and member variables Name, write Name = Name is obviously not allowed, in the parameter or local variable name and class member variable At the time, due to the high priority of the parameters or local variables, the parameter name or partial variable name in the method body will hide the member variable of the same name, so for the value name member variable, you must specify the current object using this.

转载请注明原文地址:https://www.9cbs.com/read-47434.html

New Post(0)