super说到底就是调用父类的东西,只能在继承关系中使用,关键还是对比this关键字来看。
看代码:
调试类:
package com.oop.demo05;
public class Demo {
public static void main(String[] args) {
Student student = new Student();
System.out.println("===================================");
student.test1("华子");
student.test2();
}
}
Person类:
package com.oop.demo05;
public class Person {
protected String name = "芝麻干";
public Person() {
System.out.println("父类无参构造执行了");
}
public void say(){
System.out.println("说了一句话");
}
}
Student类:
package com.oop.demo05;
public class Student extends Person {
public String name = "Student";
public Student() {
// 这里隐藏了一句代码,调用了父类的构造器:super();
super();//必须放在构造器的第一行
System.out.println("子类无参构造执行了");
}
public void say(){
System.out.println("叫了一声");
}
public void test1(String name){
System.out.println(name);
System.out.println(this.name);
System.out.println(super.name);
System.out.println("=============");
}
public void test2(){
super.say();
say();
this.say();
}
}
运行结果:
一个一个来看:
输出结果:
这表明,name为形式参数,this.name为子类中的属性, super.name就是父类中的属性。
再看下一步:
1.
2.调用了say()、this.say(); 、super.say();
输出结果:
最后调用子类的构造器:
输出结果:
先行调用了父类的构造器。
如上,这就突出了super的特点:
- super调用父类的构造方法,必须放在子类构造器的第一行。
- 且和this关键字不能同时调用。
- 且只能出现在子类的构造器或方法中。
总结一下和this关键字的区别:
1.代表的对象不同:
- this本身调用 者这个对象
- super代表父类对象的应用
2.前提:
- this:没有继承也可以使用
- super:只能在继承条件才可以使用
3.构造方法:
- this() ;本类的构造
- super() :父类的构造



