【问题标题】:How do I use the "this" keyword in java?如何在 java 中使用“this”关键字?
【发布时间】:2014-09-27 15:22:03
【问题描述】:

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

【问题讨论】:

标签: java this


【解决方案1】:

java中的这个

用于在被调用的方法或构造函数中引用对象的数据成员,以防字段与局部变量发生名称冲突

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

【讨论】:

  • 在最后一个示例的main 方法中,您可以将Swapper 分配给一个变量(或做类似的事情),这样return this 行就有用处了。跨度>
  • 那么“this”用于多个构造函数?如果是这样,那你为什么需要多个构造函数?
【解决方案2】:

这是一对:

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指的是属于使用this的对象的属性。例如:

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

在这些情况下,ex1.getA() 将返回 3,因为this 指的是属于名为ex1 的对象的a,而不是ex2 或其他任何东西。 ex2.getB() 也是如此。

如果您查看setA()setB() 方法,使用this 将属于对象的属性ab 与参数名称区分开来,因为它们是相同的。

【讨论】:

  • 您能解释一下“this”关键字的用途吗?我不知道该怎么处理它
  • this 是对自身的引用
  • 对不起,“本身”是什么
  • 我在回答中添加了更多细节
猜你喜欢
  • 2010-10-09
  • 1970-01-01
  • 1970-01-01
  • 2011-01-26
  • 2014-04-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多