码迷,mamicode.com
首页 > 其他好文 > 详细

this怎么用(基础)

时间:2018-07-12 10:29:00      阅读:200      评论:0      收藏:0      [点我收藏+]

标签:stat   赋值   一个   ack   方法   int   ima   基础   公司   

this关键字的概述

    this关键字代表是对象的引用。也就是this在指向一个对象,所指向的对象就是调用该函数的对象引用。

this关键字作用

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

例: 使用java类描述一个动物。
问题:存在同名的成员变量与局部变量时,在方法的内部访问的是局部变量(java 采取的是就近原则的机制访问的。)


  1. class Animal{


  2. String name ;  //成员变量


  3. String color;


  4. public Animal(String n , String c){

  5. name = n;

  6. color = c;

  7. }


  8. //this关键字代表了所属函数的调用者对象

  9. public void eat(){

  10. //System.out.println("this:"+ this);

  11. String name = "老鼠"; //局部变量

  12. System.out.println(name+"在吃..."); //需求: 就要目前的name是成员变量的name.


  13. }

  14. }


  15. class Demo6

  16. {

  17. public static void main(String[] args)

  18. {

  19. Animal dog = new Animal("狗","白色");  //现在在内存中存在两份name数据。


  20. Animal cat = new Animal("猫","黑色");

  21. cat.eat();

  22. }

  23. }

this关键字调用其他的构造函数要注意的事项

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


例:


  1. class Student{


  2. int id;  //×××


  3. String name;  //名字


  4. //目前情况:存在同名 的成员 变量与局部变量,在方法内部默认是使用局部变量的。

  5. public Student(int id,String name){  //一个函数的形式参数也是属于局部变量。

  6. this(name); //调用了本类的一个参数的构造方法

  7. //this(); //调用了本类无参的 构造方法。

  8. this.id = id; // this.id = id 局部变量的id给成员变量的id赋值

  9. System.out.println("两个参数的构造方法被调用了...");

  10. }



  11. public Student(){

  12. System.out.println("无参的构造方法被调用了...");

  13. }


  14. public Student(String name){

  15. this.name = name;

  16. System.out.println("一个参数的构造方法被调用了...");

  17. }


  18. }



  19. class Demo{

  20. public static void main(String[] args) {

  21. Student s = new Student(110,"铁蛋");

  22. System.out.println("编号:"+ s.id +" 名字:" + s.name);

  23. /*


  24. Student s2 = new Student("张三");

  25. System.out.println("名字:" + s2.name);

  26. */

  27. }

  28. }


this关键字要注意事项

1. 存在同名的成员变量与局部变量时,在方法的内部访问的是局部变量(java 采取的是“就近原则”的机制访问的。)
2. 如果在一个方法中访问了一个变量,该变量只存在成员变量的情况下,那么java编译器会在该变量的前面添加this关键字。


总结

实际工作中,存在着构造函数之间的相互调用,但是构造函数不是普通的成员函数,不能通过函数名自己接调用

所以sun公司提供this关键字。

this是什么

       1:在构造函数中打印this

       2:创建对象,打印对象名p

       3:this和p是一样的都是内存地址值。

       4:this代表所在函数所属对象的引用。


this怎么用(基础)

标签:stat   赋值   一个   ack   方法   int   ima   基础   公司   

原文地址:http://blog.51cto.com/13797478/2140687

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!