读书人

Java this 那些事情

发布时间: 2013-03-13 10:56:58 作者: rapoo

Java this 那些事儿

本我过去在哪里,自我即应在哪里。---弗洛伊德

总要有个事物来代表类的当前对象,就像C++中的this指针一样,Java中的this关键字就是代表当前对象的引用。

它有三个主要的作用:

1、在构造方法中调用其他构造方法。

比如有一个Student类,有三个构造函数,某一个构造函数中调用另外构造函数,就要用到this(),而直接使用Student()是不可以的。

2、返回当前对象的引用。

3、区分成员变量名和参数名。

看下面的例子:

public class Student{private String name;private int age;private String college;public Student(){age = 20;}public Student(String name){this();//can not be call Student,only use this() method.this.name = name;System.out.println("this student name is "+name);}public Student(String name,String college){this(name);//C++中可以直接用Student(name)调用其他构造函数this.college = college;System.out.println("this student name is "+name+" college is "+college);}public Student upgrade(){age++;return this;}public void print(){System.out.println("name is: "+name+" age is: "+age+" college is: "+college);}public static void main(String[] args){Student student1 = new Student("linc");Student student2 = new Student("linc","shenyang college");student2.upgrade().print();}}

迷失在茫茫的对象海洋时,不要忘了用this来找到自我。


读书人网 >编程

热点推荐