首先还是来看一下例子:
package thisExample;
public class Student {
private String name;
private Long id;
public Student () {
}
public Student (Long id) {
this();
this.id = id;
}
public Student (Long id, String name) {
this(id);
this.name = name;
}
public void print () {
System.out.println("A method of super class");
}
}
package thisExample;
public class MiddleStudent extends Student {
private String book;
public MiddleStudent () {
}
public MiddleStudent (Long id, String name) {
super(id, name);
}
public MiddleStudent (Long id, String name, String book) {
this(id, name);
this.book = book;
}
public void print () {
System.out.println("Override the super class method!");
}
public void show () {
this.print(); //这里为了区分比较,没有将this取消掉
super.print();
System.out.println("A method of sub class");
}
}
package thisExample;
public class StudentTest {
public static void main(String[] args) {
MiddleStudent ms = new MiddleStudent();
ms.show();
}
}
// 输出结果:Override the super class method!
// A method of super class
// A method of sub class
1.首先看一下超类Student类中用到的this,有两种用法,一种是this()
或者this(para...)
;另外一种是this.para
。
第一种情况只能用在构造器中,也就是一个构造器可以调用另一种构造器,但是构造器不能调用自己本身,也就是不能在构造器中形成递归;
第二种情况是调用当前类的成员变量和方法。在类中构造器或非构造器方法中都可以使用。其实个人觉得第二中情况一般都是使用this调用当前类的变量,来区分与变量同名的方法参数,当调用方法的时候,this可以直接省略掉。。。
2.接着看一下Student的子类MiddleStudent,是怎样调用this和super的。
this(para...)
的用法还是不变的,这里主要比较一下this(para...)
和super(para...)
。
看上面两个图就很明显,super(para...)
调用的是父类的构造器,而this(para...)
调用的是当前对象的构造器。
我们都知道不管是super(para...)
还是this(para...)
都只能放在构造器的第一行,所以他俩不能混用,反正就是一个构造器只能调用他俩之中的一个。
super可以调用父类所有非私有的成员变量和方法,这时就不能像this调用方法那么任性可以取消的,如果想调用父类的方法,必须加上super。
写到这里大家应该都清楚这两个用法和区别了,以后遇到其他的再补充。