this在java中怎么用

this关键字代表当前对象的引用,用于访问成员变量、方法和构造函数:访问成员变量:this.memberName调用成员方法:this.methodName调用构造函数:this(arguments)

this在Java中的用法

什么是this?

this关键字代表当前对象的引用。它用于访问当前对象的方法、变量和构造函数。

语法

this.memberName

其中,memberName是可以访问的成员(方法、变量或构造函数)。

用法

1. 访问成员变量:

public class Person {
    private String name;

    public Person(String name) {
        this.name = name;
    }

    public String getName() {
        return this.name;
    }
}

2. 调用成员方法:

public class Calculator {
    public int add(int a, int b) {
        return this.sum(a, b);
    }

    private int sum(int a, int b) {
        return a + b;
    }
}

3. 调用构造函数:

public class Animal {
    private String type;

    public Animal(String type) {
        this.type = type;
    }

    public Animal(String type, int age) {
        this(type); // 调用有参构造函数
    }
}

注意事项

  • this关键字只能在非静态上下文中使用,例如实例方法或构造函数中。
  • 在使用this之前,必须对对象进行实例化。
  • this用于区分当前对象与其他对象。