子类实例化过程

1.生成子类的过程

2.使用super调用父类构造函数的方法

 

上一节是用extends继承父类的 成员变量 和 成员函数, 但不能继承构造函数!!!

 

1.生成子类的过程

      Person.java

      class Person{
        String name ;
        int age ;
    
        Person(){
            System.out.println("Person的无参数构造函数");
        }
    
        Person(String name, int age){
            this.name = name ;
            this.age = age ;
            System.out.println("Person的有参数构造函数");
        }
    
        void eat(){
            System.out.println("吃饭");
        }
  }

     Student.java

     class Student extends Person{
      Student(){
          System.out.println("Student heheh");
      }
  }

     Test.java

     class Test{
      public static void main(String args []){
           Student student = new Student();
     }
  }

    

      结果先打印出了“Person的无参数构造函数”

      这是因为在子类的构造函数中, 必须调用父类的构造函数. 调用方法就是用super()函数 , 编译器会自动加上!

      class Student extends Person{

            int grade;


        Student(){

                 super();   //调用父类的无参数构造函数Person()

                               //super(String name, int age) 的话会调用Person(String name, int age)
             System.out.println("Student heheh");
        }

           

            Student( int grade ){

                 this();     //调用同类的无参数构造函数

            }
  }

    

       

     

 

 

posted @ 2014-05-18 23:26  Mirrorhanman  阅读(347)  评论(0编辑  收藏  举报