super:可以用来修饰属性、方法、构造器
1)当子类与父类中有同名的属性时,可以通过“super.此属性”显式的调用父类中声明的属性。若想调用子类的同名的属性“this.此属性”。
2)当子类重写父类的方法以后,在子类中若想再显式的调用父类的被重写的方法,就需要使用“super.方法”。
3)super修饰构造器,通过在子类中使用“super(形参列表)”来显式的调用父类中指定的构造器。
注意:在构造器内部,”super(形参列表)”必须要声明在首行!
注意:在构造器内部,“this(形参列表)”或者“super(形参列表)”只能出现一次!
注意:当构造器中,不显式的调用“this(形参列表)”或者“super(形参列表)”其中任何一个,默认调用的是父类空参的构造器!
super() 和this()很像只不过 super是父类,this是用在当前类中。
public static void main(String[] args) {
//student st = new student();
// st.show();
student s1 = new student("小东东",12);
s1.show();
}
结果是:
这是person空参的构造器
这是子类的属性:张小明1
这是子类的属性:11002
这是父类的属性:学习第一名
这是父类的属性:1000
这是子类的方法:张小明1
这是子类的方法:11002
这是父类的方法:学习第一名
这是父类的方法:1000
person 类
public class person {
public String name;//称号
int id;//序号
//构造
public person(){
System.out.println("这是person空参的构造器");
name = "学习第一名";
id = 1000;
}
//构造
public person(String name, int id) {
this.name = name;
this.id = id;
}
public void setName(String name){
this.name = name;
}
public void setId(int id){
this.id = id;
}
public String getName() {
return name;
}
public int getId() {
return id;
}
}
student - 类
public class student extends person {
public String name;//学生姓名
int id;//学生学号
public student(){
//super();//构造父类
this.name = "张小明";
this.id = 1002;
}
public student(String name,int id){
//super(name,id);//构造父类
this.name = "张小明1";
this.id = 11002;
}
public void setname(String name){
this.name = name;
}
public void setid(int id){
this.id = id;
}
//重写父类里的getName
public String getName() {
return name;//获取到当前 张小明
}
public int getId() {
return id;//获取到当前 id
}
public void show(){
System.out.println("这是子类的属性:"+this.name);
System.out.println("这是子类的属性:"+this.id);
System.out.println("这是父类的属性:"+super.name);
System.out.println("这是父类的属性:"+super.id);
System.out.println("这是子类的方法:"+getName());
System.out.println("这是子类的方法:"+getId());
System.out.println("这是父类的方法:"+super.getName());
System.out.println("这是父类的方法:"+super.getId());
}
}