(Chapter 5) java object-oriented Summary of the role of this, java object-oriented
This keyword always points to the object that calls this method.
This can represent any object. When this occurs in a method body, the object it represents is uncertain, but its type is definite, the object represented by it can only be of the current class (that class is in that class), only when
When a method is called, the objects it represents are determined. This indicates who is calling this method.
> Reference the data being initialized by the constructor
> Reference the object that calls the method in the Method
The biggest function of this keyword is to allow a method in the class to access another method or instance variable in the class.
Public class Dog {public void jump () {system. out. println ("executing the jump () method");} public void run () {// this reference calls the object in the run () method
// This indicates the run () object
This. jump ();}}
This indicates the object being initialized by the constructor.
Public class Test {// define a foo member variable public int foo; public ThisInContructor () {// define a foo local variable int foo = 0 in the constructor; // use this to indicate the object being initialized by the constructor. // The following Code sets the foo member variable of the object being initialized by the constructor to 6 this. foo = 6;} public static void main (String [] args) {// output 6 System. out. println (new ThisInContructor (). foo )}}
If the method has a local variable with the same name as the member variable, and the program needs to access this overwritten member variable, this must be used.
Public class Test {private String name = ""; private static double price = 78.0; public static void main (String [] args) {int price = 65; // output 65, local variables overwrite the member variable System. out. println (price); // outputs the 78.0 System. out. println (Test. price); // run the info () method new Test.info ();} public void info () {String name = "James"; // output James System. out. println (name); // use this as the limitation of the name variable // output, Li Gang System. out. println (this. name );}}