public class TestDate{
public static void main(String[] args){
Dog d=new Dog("bone","black",20);
d.f();
}
}
class Animal{
String color;
int height;
Animal(String c,int h){
color=c;
height=h;
System.out.println("调用父类构造函数:"+"color="+color+" height="+height);
}
}
class Dog extends Animal{
String enjoy;
Dog(String e,String c,int h){
super(c,h);
enjoy=e;
System.out.println("调用自身构造函数:"+"enjoy="+enjoy+" color="+color+" height="+height);
}
void f(){
System.out.println("调用f()方法:The dog enjoy eating bone!");
}
}
运行结果:
调用父类构造函数:color=black height=20
调用自身构造函数:enjoy=bone color=black height=20
调用f()方法:The dog enjoy eating bone!
继承中的构造方法总结:
1、子类的构造的过程中必须调用其父类的构造方法。
2、子类可以在自己的构造方法中实用super(参数列表)调用基类的构造方法,(注意“参数列表”必须与父类的“参数列表”相对应):
(1)使用 this(参数列表)调用本类的另外的构造方法;
(2)如果调用super,必须写在子类构造方法中的第一行。
3、如果子类的构造方法中没有显示地调用基类的构造方法,则系统默认调用基类无参数的构造方法(前提是基类中写了无参数构造方法或基类中没有显示地写任何构造方法)。
---------------------------------------------------------------------------------------------------------------
java code:
public class TestDate{
public static void main(String[] args){
Dog d=new Dog("bone","black",20);
d.f();
}
}
class Animal{
String color;
int height;
Animal(){ //构造函数一
System.out.println("调用父类无参数构造函数");
}
Animal(String c,int h){//构造函数二
color=c;
height=h;
System.out.println("调用父类构造函数:"+"color="+color+" height="+height);
}
}
class Dog extends Animal{
String enjoy;
Dog(String e,String c,int h){
//super(c,h);
enjoy=e;
System.out.println("调用自身构造函数:"+"enjoy="+enjoy+" color="+color+" height="+height);
}
void f(){
System.out.println("调用f()方法:The dog enjoy eating bone!");
}
}
运行结果:
调用父类无参数构造函数
调用自身构造函数:enjoy=bone color=null height=0
调用f()方法:The dog enjoy eating bone!
---------------------------------------------------------------------------------------------------------------
4、如果子类构造方法中既没有显示地调用基类构造方法,而基类中又没有写无参数的构造方法,则编译器报错!
5、还有什么需要注意的要总结……?大家一起归纳一下:)
6、由于本人还是新手,有什么错误的地方,欢迎指出来一起讨论:)