继承中的构造方法调用

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、由于本人还是新手,有什么错误的地方,欢迎指出来一起讨论:)

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值