在Java类中使用super来调用父类中的指定操作:
1.super可用于访问父类中定义的属性
2.super可用于调用父类中定义的成员方法
3.super可用于在子类构造器中调用父类的构造器
调用父类的方法或属性:
实例1:调用父类的方法
package com.qwy;
class Person {
protected String name = "张三";
protected int age;
public String getInfo() {
return "Name: " + name + "\nage: " + age;
}
}
class Student extends Person {
protected String name = "李四";
private String school = "清华大学";
public String getSchool() {
return school;
}
public String getInfo() {
//调用父类的getInfo()方法
return super.getInfo() + "\nschool: " + school;
}
}
public class StudentTest {
public static void main(String[] args) {
Student st = new Student();
System.out.println(st.getInfo());
}
}
运行结果:
Name: 张三
age: 0
school: 清华大学
注意:
当子父类出现同名成员时,可以用super表明调用的是父类中的成员 。
super和this的用法相像,this代表本类对象的引用,super代表父类的内存 空间的标识。
调用父类的构造器:
1.子类中所有的构造器默认都会访问父类中空参数的构造器
2.当父类中没有空参数的构造器时,子类的构造器必须通过this(参 数列表)或者super(参数列表)语句指定调用本类或者父类中相应的 构造器。同时,只能”二选一”,且必须放在构造器的首行
3.如果子类构造器中既未显式调用父类或本类的构造器,且父类中又没有无参的构造器,则编译出错
实例2:定义父类
package com.qwy;
import java.util.Date;
public class Person {
private String name;
private int age;
private Date birthDate;
public Person(String name, int age, Date d) {
this.name = name;
this.age = age;
this.birthDate = d;
}
public Person(String name, int age) {
//调用自己的构造方法
this(name, age, null);
}
public Person(String name, Date d) {
//调用自己的构造方法
this(name, 30, d);
}
public Person(String name) {
//调用自己的构造方法
this(name, 30);
}
}
实例:定义子类
package com.qwy;
public class Student extends Person {
private String school;
public Student(String name, int age, String s) {
// 调用父类构造方法
super(name, age);
school = s;
}
public Student(String name, String s) {
// 调用父类构造方法
super(name);
school = s;
}
//下面构造方法,没有显示调用父类构造方法,又因为父类没有无参构造,所以编译错误
/*public Student(String s) {
school = s;
}*/
}
this和super的区别: