类的构造的过程中必须调用其基类的构造方法
*子类可以在自己的构造方法中使用super调用基类的构造方法
(使用this调用本类的另外的构造方法)
如果调用super,必须写在子类构造方法的第一位上
*如果子类没有显示调用基类的构造方法,系统默认使用基类的无参构造方法
*如果子类既无显示调用基类的构造方法,而系统又没有无参构造方法,那编译错误
实例:
//定义测试类PersonText。。。
public class PersonText {
public static void main(String[] args) {
//实例化Person类 p1,p2
Person p1=new Person("A");
Person p2=new Person("B","shanghai");
//实例化student s1,s2
Student s1=new Student("C", "s1");
Student s2=new Student("C", "shanghai","s2");
System.out.println(p1.info());
System.out.println(p2.info());
System.out.println(s1.info());
System.out.println(s2.info());
}
}
//定义父类Person
class Person {
private String name;
private String location;
Person(String name){ //父类构造函数
this.name=name;
location="beijing";
}
Person(String name,String location){
this.name=name;
this.location=location;
}
public String info(){ //父类中你的方法info
return "name:"+name+"\tlocation:"+location+"\t";
}
}
//子类Student 继承父类Person
class Student extends Person{
private String school;
Student(String name,String school) {//子类中的构造方法
this(name,"beijing",school);
}
Student(String n,String l,String school){
super(n,l);
this.school=school;
}
public String info(){
return super.info()+"school:"+school;
}
}
|