Java中的this用于类中的方法体内,当一个对象被创建后,Java虚拟机就会给这个对象分配一个引用自身的指针,这个指针的名字就是this,this指向对象本身,this主要可以实现一下三个方面的功能!!
当类中使用类成员变量时,引方式是this.变量名(注意:点号!!),一般情况下,可以把this省略。但是当成员方法或构造方法中的局部变量与类成员变量同名时,类的成员变量就会被隐藏!此时,若要访问类的成员变量,则必须要有“this.变量名”的方式显示调用成员变量!
- public class Book{
- public String title;
- public Book (String title) {
- this.title=title;
- }
- }
上述代码段中的:this.title=title; 语句的含义就是将参数:title 的赋值给对象的成员变量title,关键字this代表了实列化Book的当前对象!
this可以用在构造方中, 以调用一个类中的另一个构造方法,必须注意的是,调用时this必须放法在方法的第一句!
下面笔者用代码来举列一下:this调用构造方法!
- public class Book{
- public String title;
-
- public Book (String title) {
- this.title=title;
- }
-
- public Book() {
- this("面向对象编程!");
- }
-
- public void printTitle() {
- System.out.println(title);
- }
-
- public static void main(String[] args) {
- Book book1 =new Book();
- book1.printTitle();
- }
-
- }
上述代码的运行结果为:

在上述代码中,Book类中,有两个重载的构造方法,当实列化book1对象时,调用用的是无参构造方法,其中,无参构造方法内部的第一句是调用对应的有参构造方法,设置title的值为:“面向对象编程”,因此,book1对象的printTitle()方法输出的值为:“面向对象编程”!
this可以把当前对象的引用作为参数传递给其他对象或方法,这种情况发生在两个类之间互相传递对方的信息,如方法或变量等!
下面用代码讲解一下:
- class Container {
- Component comp;
- public void addComponent() {
- comp = new Component(this);//将this作为对象引用传递
- }
- }
-
- class Component {
- Container myContainer;
- public Component(Container c) {
- myContainer = c;
- }
-
- public static void main(String[] args) {
- Container c1 = new Container();
- c1.addComponent();
- }
-
- }
对于上述的代码:容器类 Container 里面有个方法:addComponent ,含义是将组件加入当前这个容器对象,因此需要实列化租价 类 Component , Component类是一个组件类,当他在实列化时必须依附于一个容器,因此在构造函数需要传递一个容器对象,当:new Component(this) 中的this作为实列化组件时,指定其依附的容器对象就是当前的容器对象!!