JAVA中this关键字

一.  this.成员变量

二.  this.成员方法

三.  this( ) 


this关键字就是引用当前对象以及构造方法调用

1. this.成员变量

我们先看一下,下面这段代码

public class Date {
    public int year;
    public int month;
    public int day;

    public void setDate(int y,int m,int d){
        year = y;
        month = m;
        day = d;
    }

    public void printDate(){

        System.out.println(year+"年"+month+"月"+day+"日");
    }

}
public class Test {
    public static void main(String[] args) {
       Date date = new Date();
       date.setDate(1111,11,1);
       date.printDate();

        System.out.println("===========");


        Date date2 = new Date();
        date2.setDate(2222,22,2);
        date2.printDate();

    }
}

运行结果如下:

看到这个结果后我们会思考: 这段代码没有用到this关键字,那 setDate和printDate是如何知道我每次赋值和打印的是那个对象。同时我们会发出疑问,既然这种写法我们可以成功为不同对象的成员变量赋值,那为啥还要引入this.成员变量

其实this是"成员方法"第一个隐藏的参数,编译器会自动传递,在成员方法执行时,编译器会负责将调用成员方法对象的引用传递给该成员方法,this负责来接收,同时将this参数还原,在方法中的所有"成员变量"都通过this引用来访问。

接着通过下面代码,我们就可以明白为什么最好要添加this

public class Date {
    public int year;
    public int month;
    public int day;

    public void setDate(int year,int month,int day){
        year = year;
        month = month;
        day = day;
    }

    public void printDate(){

        System.out.println(year+"年"+month+"月"+day+"日");
    }

}
public class Test {
    public static void main(String[] args) {
       Date date = new Date();
       date.setDate(1111,11,1);
       date.printDate();

        System.out.println("===========");


        Date date2 = new Date();
        date2.setDate(2222,22,2);
        date2.printDate();

    }
}

通过观察可以发现,在setDate这个方法中,形参和类的成员变量名相同。这时会出现局部变量优先的原则,出现形参给自己赋值,而成员变量里还是默认值。

最好的写法如下:

public class Date {
    public int year;
    public int month;
    public int day;

    public void setDate(int year,int month,int day){
        this.year = year;
        this.month = month;
        this.day = day;
    }

    public void printDate(){

        System.out.println(this.year+"年"+this.month+"月"+this.day+"日");
    }

}
2. this.成员方法
public class Date {
    public int year;
    public int month;
    public int day;

    public void setDate(int year,int month,int day){
        this.year = year;
        this.month = month;
        this.day = day;
    }

    public void printDate(){

        System.out.println(this.year+"年"+this.month+"月"+this.day+"日");
    }

    public void show(){
        this.printDate();
    }

}
public class Test {
    public static void main(String[] args) {
       Date date = new Date();
       date.setDate(1111,11,1);
       date.printDate();
       date.show();

        System.out.println("===========");


        Date date2 = new Date();
        date2.setDate(2222,22,2);
        date2.printDate();
        date2.show();

    }
}

本质上就是在一个成员方法中用this调用另一个成员方法,这里可以认为this具有传递性。

3. this( )

在这之前先知道对象的初始化。

我们知道,在Java方法内部定义一个局部变量时,必须初始化,否则在使用它时会编译失败。

而类中的成员变量即使未初始化,也能正常使用。

class Da_te {
    public int year;
    public int month;
    public int day;


    public void printDa_te() {

        System.out.println(this.year + "年" + this.month + "月" + this.day + "日");
    }
}
public class Test {

    public static void main(String[] args) {
       Da_te date = new Da_te();
       date.printDa_te();
    }
}

未初始化,显示的是默认值

如果我们想对对象的属性进行赋值,又不想每次赋值时都要创建一个类似setDate这样的函数,这时我们就可以用构造方法

构造方法:(本质是创建对象时初始化对象状态)
    1.名字与类名相同,没有返回值类型,设置为void也不行
    2. 一般情况下使用public修饰,若被private修饰,该类不能在其他类中使用new关键字来创建对象
    3. 在创建对象时由编译器自动调用,并且在对象的生命周期内只调用一次

    4. 构造方法可以发生重载

注意:当自己没有写构造方法时,编译器会生成一份默认的构造方法,生成的默认构造方法一定是无参的(方法体中什么也没有)。但是一旦用户定义,编译器则不在生成。

public class Date {
    public int year;
    public int month;
    public int day;

    public Date(){
        System.out.println("不带参数的构造方法");
        this.year = 2024;
        this.month = 10;
        this.day = 22;

    }
    public Date(int year,int month,int day){
        System.out.println("带参数的构造方法");
        this.year = year;
        this.month = month;
        this.day = day;

    }

    public void printDate() {

        System.out.println(this.year + "年" + this.month + "月" + this.day + "日");
    }

    public void show(){

        this.printDate();
    }

}
public class Test {

    public static void main(String[] args) {
       Date date = new Date();
       date.show();
        System.out.println("===============");
        Date date2 = new Date(2024,10,22);
        date2.show();

    }
}

最后我们引入this( )。在构造方法中,可以通过this()调用其他构造方法来简化代码。

其实这就是this( )的主要用途。

public class Date {
    public int year;
    public int month;
    public int day;

    public Date() {
        this(2024,10,22);
    }

    public Date(int year, int month, int day) {
        System.out.println("带参数的构造方法");
        this.year = year;
        this.month = month;
        this.day = day;
    }

    public void printDate() {

        System.out.println(this.year + "年" + this.month + "月" + this.day + "日");
    }

    public void show(){

        this.printDate();
    }

}

需要注意的是:this( )必须是构造方法中的第一条语句!!!!!

                      同时使用this( )时,不能形成环!!!!!

这种代码编译都过不去

<think>我们正在讨论Java中的`this`关键字。根据引用的资料,`this`关键字主要有四种用法: 1. 引用当前对象的成员变量(解决局部变量与成员变量同名的问题) 2. 调用当前对象的成员方法(通常可以省略,但有时为了明确也可使用) 3. 调用当前类的其他构造方法(使用`this(...)`形式,且必须位于构造方法的第一行) 4. 返回当前对象的引用(在方法中返回`this`) 此外,引用[3]还解释了`this`是成员方法的隐藏参数,编译器自动将调用该方法的对象引用传递给方法,并用`this`来接收。 接下来,我们将详细解释这些用法,并给出示例代码。 ### 一、`this`关键字概述 在Java中,`this`关键字代表当前对象的引用。它只能在类的非静态方法或构造方法中使用。其主要作用是在对象内部引用自身的成员(变量或方法),特别是在局部变量与成员变量同名的情况下,使用`this`可以明确指定成员变量。 ### 二、`this`关键字的四种用法 #### 1. 区分成员变量和局部变量 当方法的形参或局部变量与成员变量同名时,使用`this`关键字来访问成员变量。 ```java public class Student { private String name; public void setName(String name) { this.name = name; // 使用this.name表示成员变量,name是形参 } } ``` #### 2. 调用当前对象的其他方法 在类的成员方法中,可以使用`this`来调用当前对象的其他方法。实际上,在调用本类的方法时,`this`通常是隐含的,可以省略。但有时为了明确调用者是当前对象,也会加上。 ```java public class MyClass { public void method1() { System.out.println("Method1"); } public void method2() { this.method1(); // 显式使用this调用method1 // 或者直接调用:method1(); } } ``` #### 3. 调用本类的其他构造方法(构造器重载) 在一个构造方法中,可以使用`this(...)`来调用本类的其他构造方法。注意: - 必须在构造方法的第一行。 - 不能循环调用(例如,两个构造方法互相调用)。 ```java public class Rectangle { private int width; private int height; // 无参构造方法,调用有参构造方法 public Rectangle() { this(10, 10); // 调用下面的两个参数的构造方法 } public Rectangle(int width, int height) { this.width = width; this.height = height; } } ``` #### 4. 返回当前对象的引用 在方法中,如果需要返回当前对象,可以使用`return this;`。这种方式常用于链式调用(Fluent API)的设计。 ```java public class Counter { private int count; public Counter increment() { count++; return this; // 返回当前对象 } public static void main(String[] args) { Counter c = new Counter(); c.increment().increment(); // 链式调用 } } ``` ### 三、`this`关键字的底层原理 根据引用[3],`this`实际上是成员方法的第一个隐藏参数。当调用一个成员方法时,编译器会自动将调用该方法的对象引用作为第一个参数传递进去,而`this`就是用来接收这个引用的。因此,在方法内部,所有对成员变量的访问实际上都是通过`this`引用来完成的,只是通常省略了`this`。 例如,以下代码: ```java public class Test { private int x; public void setX(int x) { this.x = x; } } ``` 在编译时,`setX`方法实际上会被处理成类似于: ```java public void setX(Test this, int x) { this.x = x; } ``` ### 四、常见误区 - **静态方法中没有`this`**:因为静态方法属于类,不属于对象,所以不能用`this`。 - **避免滥用`this`**:在不会产生歧义的情况下,可以直接访问成员变量,无需使用`this`。 ### 五、总结 `this`关键字Java中是一个非常重要的概念,主要用于: - 明确引用成员变量(解决同名问题) - 调用本类的其他构造方法(构造器重载) - 支持链式调用(返回当前对象) 理解`this`的底层原理(作为成员方法的隐藏参数)有助于深入理解Java的对象模型。 --- §§相关问题§§ 1. 为什么在静态方法中不能使用`this`关键字? 2. 如何利用`this`实现方法的链式调用? 3. `this`关键字在构造方法中调用其他构造方法时有何限制? 4. 在匿名内部类中,`this`关键字指向的是哪个对象? 5. Java中`this`关键字与Python中的`self`有何异同? </think>### Java中`this`关键字的详解 `this`是Java中用于引用当前对象的特殊关键字,在面向对象编程中扮演核心角色。根据引用内容[^1][^2][^3][^4],以下是其核心用法和作用原理: --- #### 一、`this`的四大核心用法 1. **区分成员变量与局部变量**(解决命名冲突) 当方法参数与成员变量同名时,用`this`显式指定成员变量: ```java public class Student { private String name; public void setName(String name) { this.name = name; // this.name指成员变量,name指参数[^4] } } ``` 2. **返回当前对象引用**(支持链式调用) 在方法中返回`this`可实现连续调用: ```java public class Calculator { private int value; public Calculator add(int num) { value += num; return this; // 返回当前对象[^2] } } // 调用:new Calculator().add(5).add(3); ``` 3. **调用本类构造方法**(构造器重载) 使用`this(...)`在构造方法中调用其他重载构造器(必须首行): ```java public class Rectangle { private int width, height; public Rectangle() { this(10, 10); // 调用带参构造器[^1] } public Rectangle(int w, int h) { width = w; height = h; } } ``` 4. **传递当前对象引用**(编译器隐式行为) 所有成员方法隐含第一个参数`this`,用于访问成员变量: ```java // 编译后等效代码 public void setName(Student this, String name) { this.name = name; // [^3] } ``` --- #### 二、`this`的底层原理 - **对象自引用机制** 每个对象的方法调用时,JVM自动将对象地址作为隐藏参数`this`传入方法栈帧。 - **内存模型关联** 通过`this`访问成员变量时,实际访问的是堆内存中当前对象的数据区域: ```mermaid graph LR A[方法栈帧] --> |this指针| B[堆内存对象] B --> C[成员变量name] B --> D[成员变量age] ``` --- #### 三、关键注意事项 1. **静态上下文中禁用** 静态方法(属于类)不能使用`this`,因无当前对象[^1]。 2. **避免循环构造调用** `this()`调用构造器时禁止形成环状调用链(编译错误)。 3. **内部类中的特殊语义** 在内部类中,`this`指代内部类对象;访问外部类需用`外部类名.this`。 ```java class Outer { class Inner { void print() { System.out.println(Outer.this); // 访问外部类对象 } } } ``` --- #### 四、典型应用场景 | 场景 | 代码示例 | 作用说明 | |---------------------|----------------------------------|----------------------------| | Builder模式 | `return this;` | 实现链式调用[^2] | | 对象自省 | `this.getClass().getName()` | 获取运行时类信息 | | 事件处理 | `button.addActionListener(this)`| 当前对象作为监听器 | ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值