子父类中的构造函数:
注:创建子类对象时,父类的构造函数也会运行。因为子类的构造函数默认第一行有一条隐式的语句,super();而super()会访问父类中空参数的构造函数。而且子类中所有的构造函数第一行默认都是supre();
public class Demo30 {
public static void main(String[] args){
Cat c=new Cat();
}
}
class Animal{
Animal() {
System.out.println("animal run");
}
}
class Cat extends Animal{
Cat() {
//super(); // 子类的构造函数有个隐式的语句
System.out.println("cat run");
}
}
输出结果为:
子类中所有的构造函数第一行默认都是supre();animal run
cat run
public class Demo30 {
public static void main(String[] args){
Cat c=new Cat();
Cat c1=new Cat(6);
}
}
class Animal{
Animal() {
System.out.println("animal run");
}
}
class Cat extends Animal{
Cat() {
//super(); // 子类的构造函数有个隐式的语句
System.out.println("cat run");
}
Cat(int age){
System.out.println("cat.age="+age);
}
}
输出结果为:
animal run
cat run
animal run
cat.age=6
为什么子类一定要访问父类中的构造函数:
因为父类中的数据子类可以直接获取。所以子类对象建立是,需要先查看父类是如何对这些数据进行初始化的。所以子类在对象初始化时,要先访问以下父类中的构造函数。
如果要访问父类中指定的构造函数,可以通过手动定义super语句的方式来指定。
public class Demo30 {
public static void main(String[] args){
Cat c=new Cat();
// Cat c1=new Cat(6);
System.out.println(c.age);
}
}
class Animal{
int age;
Animal() {
age=8;
System.out.println("animal run");
}
}
class Cat extends Animal{
Cat() {
//super(); // 子类的构造函数有个隐式的语句
System.out.println("cat run");
}
Cat(int age){
System.out.println("cat.age="+age);
}
}
输出结果为:
animal run
cat run
8
注意:super语句一定定义在子类的第一行。this语句也必须放在第一行,如果有this()语句,子类就没有隐含的super();(为什么this()或super()必须放在第一行,因为初始化动作要先做)
结论:
1、子类所有的构造函数,默认都会访问父类中空参数的构造函数。因为子类每一个构造函数内的第一行都有一句隐式super();
2、当父类中没有空参数的构造函数时,子类必须手动通过super或者this语句形式来指定要访问父类中的构造函数。
3、子类的构造函数第一行也可以手动指定this语句来访问本类中的构造函数。子类中至少会有一个构造函数会访问父类中的构造函数。