Java关键字this

this 关键字

在类的方法定义中使用this关键字代表使用该方法的对象的引用

在必须指出当前使用方法的对象是谁时要使用this

有时使用this可以处理方法中的成员变量和参数重名的情况

this可以看作是一个变量,它的值是当前对象的引用


public class Leaf {
    int i = 0;
    Leaf(int i) {
        this.i = i;   
    }
    Leaf increament() {
        i++;
        return this;
    }
    void print() {
        System.out.println("i = " + i);
    }
    
    public static void main(String[] args) {
        Leaf leaf = new Leaf(100);
        leaf.increament().increament().print();
    }
}

输出:  i = 102


转载于:https://my.oschina.net/xiaozhiwen/blog/661080

这是“普通文本型”问题。 在 Java 中,`this` 是一个引用变量,指向当前对象实例。它只能在实例方法、构造器或实例变量初始化中使用,不能在静态上下文中使用(如 `static` 方法或静态块)。 `this` 的主要用途包括: 1. **区分局部变量和实例变量**:当方法的参数或局部变量与实例变量同名时,使用 `this` 明确引用实例变量。 ```java public class Person { private String name; public Person(String name) { this.name = name; // this.name 表示实例变量,name 表示参数 } } ``` 2. **调用当前类的其他构造器**:在一个构造器中,可以使用 `this()` 调用本类的另一个构造器,必须放在第一行。 ```java public class Person { private String name; private int age; public Person() { this("Unknown"); // 调用另一个构造器 } public Person(String name) { this(name, 0); } public Person(String name, int age) { this.name = name; this.age = age; } } ``` 3. **将当前对象作为参数传递**:可以将 `this` 作为参数传递给其他方法或构造器。 ```java someMethod(this); ``` 4. **返回当前对象**:常用于链式调用(fluent interface)。 ```java public Person setName(String name) { this.name = name; return this; } ``` 知识点: - **`this` 关键字的作用域**:`this` 只能在实例上下文中使用,不能在 `static` 方法中使用,否则编译报错。 - **构造器重载中的 `this()` 调用**:`this()` 必须是构造器中的第一条语句,且最多调用一次。 - **`this` 作为对象引用**:`this` 指向当前实例,可用于方法传参或返回自身。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值