首页 > 试题广场 >

this 关键字有什么作用,请描述。

[问答题]

this 关键字有什么作用,请描述。

1 区分局部变量和实例变量 2 在实例方法中进行访问实例变量和方法 3 构造方法第一行,实现代码复用
发表于 2022-01-25 23:47:01 回复(0)
一、使用this调用本类中的成员变量(属性),下面代码就是使用this.方法(属性)进行方法(属性)调用
class Student { private String name; public void setName(String name){ this.print();//调用本类中的print方法  } public String getName(){ return "姓名:" + name;  } public void print(){
        System.out.println("设置相关信息如下……");  }
}
二、使用this调用构造方法
       我们可以对类的构造方法进行重载,可以在构造方法中调用其他构造方法
class Student { private String name;  private int age;   public Student() { this("李明", 20);//调用有两个参数的构造方法  System.out.println("新对象实例化");  } public Student(String name) { this();  } public Student(String name, int age) { this(name);  this.age = age;  } public String getInfo() { return "姓名:" + name + ",年龄:" + age;  }
}
三、使用this引用当前对象
this关键字除了可以引用变量或者成员方法之外,还有一个重大的作用就是返回类的引用。如在代码中,可以使用return this,来返回某个类的引用。此时这个this关键字就代表类的名称。如代码在上面student类中,那么代码代表的含义就是return student。
发表于 2017-01-22 12:08:07 回复(1)