java this 关键字

来源:互联网 发布:淘宝确认开店协议 编辑:程序博客网 时间:2024/06/06 19:14

1 表示当前类的属性和调用方法

2 调用本类的构造方法

3 表示当前对象

案例 一

package csdn.zyl.demo;
class People4{
 private String name;
 private int age;
 public People4(String name,int age){
  this();//有参数构造 函数 中 调用 无参构造 函数执行 
  this.age=age;
  this.name=name;
 }
 public People4(){
  System.out.println("无参数的构造方法");
 }
 
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;//this 使用本类的属性
 }
 public int getAge() {
  return age;
 }
 public void setAge(int age) {
  this.age = age;
 }
 public void tell()
 {
   //this使用本类中的方法
  System.out.println("姓名:"+this.getName()+"年龄:"+this.getAge());
 }
}
public class ThisDemo {
 
 public  static void main(String[] args) {
  People4 people = new People4("张三",33);
  people.tell();
 }
}

结果如下 :

无参数的构造方法
姓名:张三年龄:33


案例 2 :

package csdn.zyl.demo;
class People12{
 public void tell()
 {
  System.out.println(this);//使用this获得当前对象
 }
}
public class ThisDeno1 {
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  People12 people = new People12();
  System.out.println(people);
  people.tell();
  
 }
}

结果如下:

csdn.zyl.demo.People12@15db9742
csdn.zyl.demo.People12@15db9742