"Java basics of" Java this keyword Detailed

One example of this keyword is used to indicate the current object itself, or the current class, all methods and properties can be called by this object.

E.g:

public  class Demo {
     Private  int X = 10 ;
     Private  int Y = 15 ; 

    public  void SUM () {
         // Get member variables through this, this may be omitted. 
        int Z = the this .x + the this .y;    
        System.out.println ( "X + = Y" + Z); 
    } 

    public  static  void main (String [] args) { 
        Demo Demo = new new Demo (); 
        demo.sum (); 
    } 
}

operation result:

Use this to distinguish between variables with the same name

public  class Demo {
     Private String name;
     Private  int Age; 

    public Demo (String name, int Age) {
         // the this can not be omitted, this.name refers to a member variable equal to the variable name is passed back to the parameter, the this can good name to distinguish between the same two variables case. 
        the this .name = name;
         the this .age = Age; 
    } 
    public  static  void main (String [] args) { 
        Demo Demo = new new Demo ( "micro Institute",. 3 ); 
        System.out.println (demo.name + "in age "+ demo.age); 
    } 
}

operation result:

As the name of this method to initialize the object

public  class Demo {
     Private String name;
     Private  int Age; 

    public () {Demo
         / ** 
         call another constructor * constructor, invoke actions must be placed in the best starting position. 
         * You can not call the constructor outside of the constructor. 
         * A constructor can only be called a constructor. 
         * / 
        The this ( "micro Institute",. 3 ); 
    } 

    public Demo (String name, int Age) {
         the this .name = name;
         the this .age = Age; 
    } 

    public  static  void main (String [] args) { 
        Demo Demo = newDemo (); 
        System.out.println (demo.name + "Age is" + demo.age); 
    } 
}

operation result:

 this passed as parameters

class Person{    
    public void eat(Apple apple){
        Apple peeled = apple.getPeeled();
        System.out.println("Yummy");
    }
}
class Peeler{
    static Apple peel(Apple apple){
        return apple;
    }
}
class Apple{
    Apple getPeeled(){
        //传入this,就是传入Apple。
        return Peeler.peel(this);
    }
}
public class This{
    public static void main(String args[]){
        new Person().eat(new Apple());
    }
}

this usage on here.

Reference: https://www.cnblogs.com/yefengyu/p/4821582.html

 

Guess you like

Origin www.cnblogs.com/jssj/p/11323948.html