简体   繁体   English

如何在java中使用“this”关键字?

[英]How do I use the “this” keyword in java?

我一直在使用多种方法,但是我的“java 完整参考”一书并没有很好地解释如何使用“this”关键字。

this in java这个在java中

It is used to refer to the data members of the object in the envoked method or constructor in case there is a name conflict between fields and local variables用于在调用的方法或构造函数中引用对象的数据成员,以防字段和局部变量发生名称冲突

    public class Test {
    String s;
    int i; 
    public Test(String s, int i){
        this.s = s;
        this.i = i;
    } }

It is used to invoke one constructor from another constructor of the same class or you can say constructor chaining.它用于从同一类的另一个构造函数调用一个构造函数,或者您可以说构造函数链接。

public class ConstructorChainingEg{
    String s;
    int i;
    public ConstructorChainingEg(String s, int i){
        this.s = s;
        this.i = i;
        System.out.println(s+" "+i);
    }
    public ConstructorChainingEg(){
        this("abc",3); // from here call goes to parameterized constructor
    }

    public static void main(String[] args) {
       ConstructorChainingEg m = new ConstructorChainingEg();
      // call goes to default constructor
    }
}

It also facilitates method chaining它还有助于方法链接

class Swapper{
    int a,b;
    public Swapper(int a,int b){
        this.a=a;
        this.b=b;
    }
    public Swapper swap() {
        int c=this.a;
        this.a=this.b;
        this.b=c;
        return this;
    }
    public static void main(String aa[]){
        new Swapper(4,5).swap(); //method chaining
    }
}

Here's a couple:这是一对夫妇:

public class Example {
    private int a;
    private int b;

    // use it to differentiate between local and class variables
    public Example(int a, int b) {
        this.a = a;
        this.b = b;
    }

    // use it to chain constructors
    public Example() {
        this(0, 0);
    }

    // revised answer:
    public int getA() {
        return this.a;
    }

    public int getB() {
        return this.b
    }

    public int setA(int a) {
        this.a = a
    }

    public void setB(int b) {
        this.b = b;
    }
}

this refers to the attributes that belong to the object in which this is used in. For example: this指的是属于使用this的对象的属性。例如:

Example ex1 = new Example(3,4);
Example ex2 = new Example(8,1);

In these cases, ex1.getA() will return 3, because this is referring to the a that belongs to the object named ex1 , and not ex2 or anything else.在这些情况下, ex1.getA()将返回 3,因为thisa是属于名为ex1的对象的a ,而不是ex2或其他任何东西。 The same goes for ex2.getB() . ex2.getB()

If you look at the setA() and setB() methods, using this distinguishes the attributes a and b belonging to the object from the parameter names as they're the same.如果您查看setA()setB()方法,使用this可以将属于对象的属性ab与参数名称区分开来,因为它们是相同的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM