什么是this
代表指向当前类的一个引用,比如当前类是A,那么this就指代指向类A的引用。
什么是super
是一个关键字,可以指导编译器调用父类的相关的可访问资源(非private).。
特别注意!!
super并不指向父类的引用,他只是一个关键字,让你操控父类的相关资源而已,而this则指我这个类实实在在的引用,我们可以从java核心技术第一卷中的chapter5看到这句话
Some people think of super as being analogous to the this reference.
However, that analogy is not quite accurate: super is not a reference to an
object. For example, you cannot assign the value super to another object
variable. Instead, super is a special keyword that directs the compiler to
invoke the superclass method.
大概意思就是说,super不是一个对象的引用,你不能把他赋值给另一个对象变量,这是和this不一样的,我们可以写代码看看:
public class F extends SimpleDateFormat {
public void m1(){
F f = this; // 这么做是允许的
F g = super; // 这是不允许的,编译器会报错
}
public static void main(String[] args) throws IOException {
}
}
关于用法
用法的话相信大家都很清楚的,
- 用于调用构造方法
class P{
public P(){
System.out.println("P constructor invoke");
}
}
class C extends P{
public C(){
// 无参调用有参
// this("test");
// 调用父类构造
super();// 这句其实也是隐式存在的,即便你不写。
System.out.println("C constuctor invoke");
}
public C(String s){
System.out.println("C parameter constructor invoke");
}
}
- 用于调用成员方法
class P{
public void m1(){
System.out.println("p m1");
}
}
class C extends P{
public void m1(){
// 这是调用的父类的m1方法
super.m1();
}
}
- 用于调用成员变量(比如局部变量和成员变量名称冲突的时候)
class P{
String v1;
public void setV1(String v1) {
this.v1 = v1;
}
public P(){
System.out.println("P constructor invoke");
}
}
class C extends P{
String v1;
public void setV1(String v1) {
// 此处是局部变量v1赋值给此类中的v1
this.v1 = v1;
// 下面是父类中的v1赋值给此类中的v1
this.v1 = super.v1;
}
public C(){
// 无参调用有参
this("test");
System.out.println("C constuctor invoke");
}
public C(String s){
System.out.println("C parameter constructor invoke");
}
}