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

问题描述 投票:-2回答:2

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

java this
2个回答
1
投票

java中的this

用于在引用的方法或构造函数中引用对象的数据成员,以防字段和局部变量之间存在名称冲突。>

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

用于从同一个类的另一个构造函数调用一个构造函数,或者可以说构造函数链接。

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
    }
}

它也便于方法链接

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
    }
}

0
投票

这里有一对:

© www.soinside.com 2019 - 2024. All rights reserved.