java中的this详解

this关键字:this关键字代表了所属函数的调用者对象。

this关键字作用:
1. 如果存在同名成员变量与局部变量时,在方法内部默认是访问局部变量的数据,可以通过this关键字指定访问成员变量的数据。
2. 在一个构造函数中可以调用另外一个构造函数初始化对象。

this关键字调用其他的构造函数要注意的事项:
1. this关键字调用其他的构造函数时,this关键字必须要位于构造函数中的第一个语句。
2. this关键字在构造函数中不能出现相互调用的情况,因为是一个死循环。

this关键字要注意事项:
1. 存在同名的成员变量与局部变量时,在方法的内部访问的是局部变量(java 采取的是“就近原则”的机制访问的。)

2. 如果在一个方法中访问了一个变量,该变量只存在成员变量的情况下,那么java编译器会在该变量的 前面添加this关键字。

作用一:如果存在同名成员变量与局部变量时,在方法内部默认是访问局部变量的数据,可以通过this关键字指定访问成员变量的数据。

 

  1. class Person{  
  2.           
  3.     int id; //编号  
  4.   
  5.     String name; //姓名  
  6.     
  7.     int age;  //年龄  
  8.   
  9.     //构造函数  
  10.     public Person(int id,String name ,int age){  
  11.         this.id  = id;  
  12.         this.name = name;  
  13.         this.age = age;  
  14.     }  
  15.   
  16.     //比较年龄的方法  
  17.     public void compareAge(Person p2){  
  18.         if(this.age>p2.age){  
  19.             System.out.println(this.name+"大!");  
  20.         }else if(this.age<p2.age){  
  21.             System.out.println(p2.name+"大!");  
  22.         }else{  
  23.             System.out.println("同龄");  
  24.         }  
  25.     }  
  26. }  
  27.   
  28.   
  29. class Demo8{  
  30.   
  31.     public static void main(String[] args)   
  32.     {  
  33.         Person p1 = new Person(110,"狗娃",17);  
  34.         Person p2 = new Person(119,"铁蛋",9);  
  35.         p1.compareAge(p2);  
  36.   
  37.     }  
  38. }  

作用二:在一个构造函数中可以调用另外一个构造函数初始化对象

 

  1. class Student{  
  2.   
  3.     int id;  //身份证  
  4.   
  5.     String name;  //名字  
  6.   
  7.     //目前情况:存在同名 的成员 变量与局部变量,在方法内部默认是使用局部变量的。  
  8.     public Student(int id,String name){  //一个函数的形式参数也是属于局部变量。  
  9.         this(name); //调用了本类的一个参数的构造方法  
  10.         //this(); //调用了本类无参的 构造方法。  
  11.         this.id = id; // this.id = id 局部变量的id给成员变量的id赋值  
  12.         System.out.println("两个参数的构造方法被调用了...");  
  13.     }  
  14.       
  15.       
  16.     public Student(){  
  17.         System.out.println("无参的构造方法被调用了...");  
  18.     }  
  19.   
  20.     public Student(String name){  
  21.         this.name = name;  
  22.         System.out.println("一个参数的构造方法被调用了...");  
  23.     }  
  24.   
  25. }  
  26.   
  27.   
  28. class Demo7   
  29. {  
  30.     public static void main(String[] args)   
  31.     {  
  32.         Student s = new Student(110,"铁蛋");  
  33.         System.out.println("编号:"+ s.id +" 名字:" + s.name);  
  34. /* 
  35.      
  36.         Student s2 = new Student("金胖子"); 
  37.         System.out.println("名字:" + s2.name); 
  38.     */  
  39.     }  
  40. }  


本例中两个参数的构造函数public Student(int id,String name),其实内部是先通过this(name)调用一个参数的构造函数public Student(String name)

posted @ 2016-11-23 15:18  天涯海角路  阅读(223)  评论(0)    收藏  举报