Super详解
总结:
super注意点:
1. super调用父类的构造方法,必须在构造方法的第一个。
2. super必须只能出现在的方法或者构造方法中!
3. super 和 this 不能同时调用构造方法!
this 与 super 的对比:
1. 代表对象不同:
this:本身调用者(这个对象)
super: 代表父类对象的引用
2. 前提:
this:没有继承者也可以使用
super:只有在继承条件下才可以使用
3.构造方法:
this(); 本类的构造
super(); 父类的构造
示例1(参数name的继承)
测试类
public class Application {
public static void main(String[] args) {
Student student = new Student();
//测试类赋予的name:影
student.test("影");
}
}
输出结果:
影
雷神
雷电将军
学生类
public class Student extends Person {
private String name = "雷神";
public void test(String name){
//这个类是测试类赋予的名字为影
System.out.println(name);
//这个this。name是这个类(student类)所属的name
System.out.println(this.name);
//super.name是调用父类的name
System.out.println(super.name);
}
}
父类
public class Person {
protected String name = "雷电将军";
}
示例2(调用类的继承)
测试类
public class Application {
public static void main(String[] args) {
Student student = new Student();
student.test1();
}
}
输出结果:
雷神
雷神
雷电将军
学生类(子类)
public class Student extends Person {
public void print(){
System.out.println("雷神");
}
public void test1(){
print();
this.print();
super.print();
}
}
person类(父类)
public class Person {
//私有的private无法被继承
public void print(){
System.out.println("雷电将军");
}
}
示例3(继承时,隐藏的无参构造)
测试类
public class Application {
public static void main(String[] args) {
Student student = new Student();
}
}
输出结果:
Person无参执行了
Student无参执行了
学生类
public class Student extends Person {
public Student() {
//隐藏代码,调用父类的无参构造
super();//调用父类的构造器,必须要在子类构造器的第一行
System.out.println("Student无参执行了");
}
}
person类
public class Person {
//构造默认无参
public Person() {
System.out.println("Person无参执行了");
}
}
示例4(如果父类是有参构造)
测试类
public class Application {
public static void main(String[] args) {
Student student = new Student();
}
}
输出结果:
Person无参执行了
Student无参执行了
学生类
public class Student extends Person {
public Student()
super("name");//子类就得调用父类的有参
System.out.println("Student无参执行了");
}
}
person类
public class Person {
//如果定义了有参构造,则没有默认的无参构造
public Person(String name) {
System.out.println("Person无参执行了");
}
}