Java-this关键字

转载至:Java中this关键字的几种用法

当成员变量和局部变量重名时,在方法中使用this时,表示的是该方法所在类中的成员变量。(this是当前对象自己)

如:

public class Hello {
    String s = "Hello";

    public Hello(String s) {
       System.out.println("s = " + s);
       System.out.println("1 -> this.s = " + this.s);
       this.s = s;//把参数值赋给成员变量,成员变量的值改变
       System.out.println("2 -> this.s = " + this.s);
    }

    public static void main(String[] args) {
       Hello x = new Hello("HelloWorld!");
       System.out.println("s=" + x.s);//验证成员变量值的改变
    }
}

结果为:

s = HelloWorld!
1 -> this.s = Hello
2 -> this.s = HelloWorld!
s=HelloWorld!

在这个例子中,构造函数Hello中,参数s与类Hello的成员变量s同名,这时如果直接对s进行操作则是对参数s进行操作。若要对类Hello的成员变量s进行操作就应该用this进行引用。运行结果的第一行就是直接对构造函数中传递过来的参数s进行打印结果; 第二行是对成员变量s的打印;第三行是先对成员变量s赋传过来的参数s值后再打印,所以结果是HelloWorld!而第四行是主函数中直接打印类中的成员变量的值,也可以验证成员变量值的改变。

把自己当作参数传递时,也可以用this.(this作当前参数进行传递)

class A {
    public A() {
       new B(this).print();// 调用B的方法
    }
    public void print() {
       System.out.println("HelloAA from A!");
    }
}
class B {
    A a;
    public B(A a) {
       this.a = a;
    }
    public void print() {
       a.print();//调用A的方法
       System.out.println("HelloAB from B!");
    }
}
public class HelloA {
    public static void main(String[] args) {
       A aaa = new A();
       aaa.print();
       B bbb = new B(aaa);
       bbb.print();
    }
}

结果为:

HelloAA from A!
HelloAB from B!
HelloAA from A!
HelloAA from A!
HelloAB from B!

在这个例子中,对象A的构造函数中,用new B(this)把对象A自己作为参数传递给了对象B的构造函数。

有时候,我们会用到一些内部类和匿名类,如事件处理。当在匿名类中用this时,这个this则指的是匿名类或内部类本身。这时如果我们要使用外部类的方法和变量的话,则应该加上外部类的类名。

如:

public class HelloB {
    int i = 1;

    public HelloB() {
       Thread thread = new Thread() {
           public void run() {
              for (int j=0;j<20;j++) {
                  HelloB.this.run();//调用外部类的方法
                  try {
                     sleep(1000);
                  } catch (InterruptedException ie) {
                  }
              }
           }
       }; // 注意这里有分号
       thread.start();
    }

    public void run() {
       System.out.println("i = " + i);
       i++;
    }

    public static void main(String[] args) throws Exception {
       new HelloB();
    }
}

在上面这个例子中, thread 是一个匿名类对象,在它的定义中,它的 run 函数里用到了外部类的 run 函数。这时由于函数同名,直接调用就不行了。这时有两种办法,一种就是把外部的 run 函数换一个名字,但这种办法对于一个开发到中途的应用来说是不可取的。那么就可以用这个例子中的办法用外部类的类名加上 this 引用来说明要调用的是外部类的方法 run。

在构造函数中,通过this可以调用同一类中别的构造函数。

如:

public class ThisTest {
    ThisTest(String str) {
       System.out.println(str);
    }
    ThisTest() {
       this("this测试成功!");
    }

    public static void main(String[] args) {
       ThisTest thistest = new ThisTest();
    }
}

为了更确切的说明this用法,另外一个例子为:

public class ThisTest {
    private int age;
    private String str;

    ThisTest(String str) {
       this.str=str;
       System.out.println(str);
    }
    ThisTest(String str,int age) {
       this(str);
       this.age=age;
       System.out.println(age);
    }

    public static void main(String[] args) {
       ThisTest thistest = new ThisTest("this测试成功",25);

    }
}

结果为:

this测试成功
25

值得注意的是:

  1. 在构造调用另一个构造函数,调用动作必须置于最起始的位置。
  2. 不能在构造函数以外的任何函数内调用构造函数。
  3. 在一个构造函数内只能调用一个构造函数。
  4. this同时传递多个参数。

    public class TestClass {
        int x;
        int y;
    
    static void showtest(TestClass tc) {//实例化对象
       System.out.println(tc.x + " " + tc.y);
    }
    void seeit() {
       showtest(this);
    }
    
    public static void main(String[] args) {
       TestClass p = new TestClass();
       p.x = 9;
       p.y = 10;
       p.seeit();
    }
    

    }
    结果为:

    9
    10
    代码中的showtest(this),这里的this就是把当前实例化的p传给了showtest()方法,从而就运行了。

<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)`| 当前对象作为监听器 | ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值