A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 虾米吃螃蟹 中级黑马   /  2015-7-13 10:26  /  323 人查看  /  1 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 虾米吃螃蟹 于 2015-7-13 10:28 编辑
  1. </blockquote></div><div class="blockcode"><blockquote>public class Example7
  2. {
  3.        
  4.         public static void main(String [] args){
  5.                 Child ch1=new Child();
  6.                 System.out.println("分割线————————分割线");
  7.                 Child ch2=new Child(3);
  8.         }
  9. }

  10. class Child extends Person{
  11.         public Child(){
  12.                 super();
  13.         }
  14.         public Child(int b){
  15.                 System.out.println("此处为子类:"+b);
  16.         }
  17.         public void func(){
  18.                 System.out.println("b,");
  19.                
  20.         }
  21. }

  22. class Person{
  23.         public Person(){
  24.                 func();
  25.         }
  26.         public Person(int a){
  27.                 System.out.println("此处为父类:"+a);
  28.         }
  29.         public void func(){
  30.                 System.out.println("a,");
  31.         }
  32. }  
复制代码
输出为:b,
分割线————————分割线
b,
此处为子类:3
当子类Child覆盖(重写)了父类Person中的方法func(),在子类中通过super()引用父类时,输出的为子类的方法。而如果将父类中的无参构造方法删除子类的有参构造方法
  1. public Child(int b){
  2.                 System.out.println("此处为子类:"+b);
  3.         }
复制代码
会报错“[backcolor=rgba(255, 255, 255, 0.8)]Implicit super constructor Person() is undefined. [backcolor=rgba(255, 255, 255, 0.8)]Must explicitly invoke another constructor”。因为此处有隐式super()会去调用父类的无参构造方法,而报错。
因此:1、子类的构造方法会有隐式super()去调用父类的无参构造方法,而若父类中没有无参构造方法,程序会报错;
           2、当父类没有无参构造方法时,必须在子类构造方法的首行写super(参数)语句;
           3、当子类中的方法重写了父类的方法时即例中的func(),通过super()调用父类时,输出为子类的func()

1 个回复

倒序浏览
顶一个!!
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马